Prompt
How do I query a time-series database with SQL over raw and aggregated data?
Latest observation
Oct 25, 2026
OpenAI APIWeb search: off
You generally query a time-series database with standard SQL, but you choose between:
- raw data queries — read the original, timestamped rows
- aggregated queries — summarize data into buckets like 1 minute, 1 hour, etc.
1) Raw data query
Use this when you want the exact points:
SELECT time, value
FROM metrics
WHERE time >= NOW() - INTERVAL '1 hour'
ORDER BY time;
Example use cases:
- inspect individual events
- debug spikes
- export precise data
2) Aggregated query
Use SQL GROUP BY with a time-bucketing function to summarize values over fixed intervals.
Example: average per 5 minutes
SELECT
DATE_TRUNC('minute', time) AS minute_bucket,
AVG(value) AS avg_value
FROM metrics
WHERE time >= NOW() - INTERVAL '24 hours'
GROUP BY minute_bucket
ORDER BY minute_bucket;
If your DB supports bucket functions, you may use something like:
SELECT
time_bucket('5 minutes', time) AS bucket,
AVG(value) AS avg_value
FROM metrics
WHERE time >= NOW() - INTERVAL '24 hours'
GROUP BY bucket
ORDER BY bucket;
3) Choosing raw vs aggregated
- Raw data: exact timestamps, higher cardinality, larger result sets
- Aggregated data: faster to scan, easier to visualize trends, smaller result sets
4) Common patterns
Count events per minute
SELECT
DATE_TRUNC('minute', time) AS minute_bucket,
COUNT(*) AS event_count
FROM events
WHERE time >= NOW() - INTERVAL '1 day'
GROUP BY minute_bucket
ORDER BY minute_bucket;
Max value per hour
SELECT
DATE_TRUNC('hour', time) AS hour_bucket,
MAX(value) AS peak_value
FROM metrics
WHERE time >= NOW() - INTERVAL '7 days'
GROUP BY hour_bucket
ORDER BY hour_bucket;
Latest value per series
SELECT *
FROM metrics
WHERE series_id = 'abc'
ORDER BY time DESC
LIMIT 1;
5) If your database supports both raw and downsampled tables
Some time-series systems store:
- a raw table for high-resolution data
- one or more rollup tables for pre-aggregated data
Then you query:
- raw table for short windows or exact values
- rollup table for long windows or dashboarding
Example:
SELECT bucket, avg_value
FROM metrics_5m_rollup
WHERE bucket >= NOW() - INTERVAL '30 days'
ORDER BY bucket;
6) Practical tips
- Always filter by time first with
WHERE time >= ... - Use
ORDER BY timefor raw reads - Use the correct bucket size for the query’s purpose
- If performance matters, query rollups/continuous aggregates where available
If you tell me which database you’re using (TimescaleDB, InfluxDB SQL, QuestDB, Materialize, ClickHouse, etc.), I can give you the exact syntax for raw and aggregated queries.