Prompt
How do I store sensor data in a database with fast time-range queries?
Latest observation
Nov 16, 2026
OpenAI APIWeb search: off
To store sensor data efficiently for fast time-range queries, use a schema and storage pattern optimized for append-heavy writes and range scans by timestamp.
Recommended approach
1) Use a time-series-friendly table design
At minimum, each row should include:
sensor_idtimestamp- measurement fields, e.g.
value,temperature,humidity, etc.
Example:
CREATE TABLE sensor_readings (
sensor_id BIGINT NOT NULL,
ts TIMESTAMP NOT NULL,
value DOUBLE PRECISION NOT NULL
);
2) Index for your query pattern
For queries like:
SELECT *
FROM sensor_readings
WHERE sensor_id = 42
AND ts BETWEEN '2026-01-01' AND '2026-01-02'
ORDER BY ts;
use a composite index:
CREATE INDEX idx_sensor_ts
ON sensor_readings (sensor_id, ts);
Why this helps:
sensor_idfilters to one sensortslets the database quickly find rows in the requested rangeORDER BY tsis usually efficient with this index
If you often query by time across all sensors:
CREATE INDEX idx_ts
ON sensor_readings (ts);
3) Partition by time
If data volume is large, partition the table by time, such as daily or monthly partitions.
Benefits:
- faster range queries
- easier deletion/retention of old data
- smaller indexes per partition
Example conceptually:
sensor_readings_2026_01sensor_readings_2026_02
Or use native partitioning in databases that support it.
4) Consider a time-series database if scale is high
If you have:
- high ingest rate
- billions of rows
- frequent aggregations over time
then a time-series database may be better:
- TimescaleDB on PostgreSQL
- InfluxDB
- QuestDB
- ClickHouse for analytical workloads
5) Use downsampling / rollups for older data
Keep raw data for recent periods, but aggregate older data:
- per minute
- per hour
- per day
This reduces storage and speeds up long-range queries.
6) Avoid anti-patterns
Don’t:
- store all sensor data as JSON blobs if you need fast querying
- create too many indexes on a write-heavy table
- use random primary keys that hurt insert locality unless necessary
Good default design
If using PostgreSQL:
CREATE TABLE sensor_readings (
sensor_id BIGINT NOT NULL,
ts TIMESTAMPTZ NOT NULL,
value DOUBLE PRECISION NOT NULL,
PRIMARY KEY (sensor_id, ts)
);
This works well when:
- each sensor has readings over time
- queries are usually per-sensor over time ranges
If you want, I can also give you:
- a PostgreSQL-specific design with partitioning,
- a schema for multiple metrics per reading, or
- a design for very high ingest rates.