Prompt
time series storage with SQL
Latest observation
Oct 25, 2026
OpenAI APIWeb search: off
Time-series storage with SQL usually means using a relational database to store event data with a timestamp, then designing tables and indexes so inserts and time-range queries stay fast.
Core table design
A common pattern:
CREATE TABLE metrics (
ts TIMESTAMP NOT NULL,
series_id BIGINT NOT NULL,
value DOUBLE PRECISION NOT NULL,
PRIMARY KEY (series_id, ts)
);
Why this works
ts= when the measurement happenedseries_id= what metric/device/sensor it belongs toPRIMARY KEY (series_id, ts)makes lookups by series and time efficient
Typical query patterns
Last hour for one series
SELECT *
FROM metrics
WHERE series_id = 42
AND ts >= NOW() - INTERVAL '1 hour'
ORDER BY ts;
Aggregate per minute
SELECT
DATE_TRUNC('minute', ts) AS minute,
AVG(value) AS avg_value
FROM metrics
WHERE series_id = 42
AND ts >= NOW() - INTERVAL '1 day'
GROUP BY 1
ORDER BY 1;
Indexing strategy
At minimum:
PRIMARY KEY (series_id, ts)or a composite index on those columns- If queries often filter by time across all series, add an index on
ts
Example:
CREATE INDEX idx_metrics_ts ON metrics (ts);
Partitioning
For large time-series tables, partition by time:
- daily
- weekly
- monthly
This helps with:
- faster deletes/retention
- smaller indexes
- better performance for range queries
Example conceptually:
metrics_2026_01metrics_2026_02
Many databases support native partitioning:
- PostgreSQL
- MySQL
- SQL Server
- Oracle
Retention
Time-series data often expires. You can:
- drop old partitions
- archive old data to cheaper storage
- compress historical partitions if supported
Best practices
- Use the right timestamp type with timezone awareness if needed
- Keep rows narrow
- Batch inserts instead of inserting one row at a time
- Avoid too many secondary indexes
- Pre-aggregate if you often query summaries
- Consider partitioning once volume grows large
When SQL is enough vs when to use a TSDB
SQL works well if:
- data volume is moderate
- you need joins with relational data
- you want standard SQL analytics
A specialized time-series database may be better if:
- ingest volume is extremely high
- you need built-in downsampling/compression
- retention and time partitioning are the main workload
If you want, I can also give:
- a PostgreSQL-specific design,
- a MySQL design,
- schema examples for IoT metrics, or 4. a partitioning + retention strategy.