Time Bucketing: DATE_TRUNC GROUP BY in SQL
Monthly rollups, 7-day windows, half-open buckets
Bucket time with DATE_TRUNC('month', created_at) then GROUP BY the bucket — monthly revenue, signups, retention cohorts. Day ranges stay half-open for timestamp safety. Funnel/pivot variants add FILTER (WHERE …) per bucket. Time-zone display converts at the edge (AT TIME ZONE) while storage stays UTC.
Truncate to bucket
DATE_TRUNC(month, ts) collapses to month starts for GROUP BY.
Range half-open inside
Day filters stay >= start AND < next — timestamp-safe.
Pivot per bucket
FILTER/COUNT per bucket in one scan — no N queries.
Zone on display
UTC storage; AT TIME ZONE converts. Index expression or range raw.
1SELECT DATE_TRUNC('month', created_at) AS m, COUNT(*) AS orders FROM orders GROUP BY m ORDER BY m;
| month | orders |
|---|---|
| 2024-01-01 | 2 |
| 2024-02-01 | 1 |
Timestamps collapse to month starts, then group. Same shape with FILTER splits premium vs standard per month in one scan — no N queries.
Monthly order counts
Two buckets from three rows.
1SELECT DATE_TRUNC('month', created_at) AS m, COUNT(*) AS orders FROM orders GROUP BY m ORDER BY m;
| month | orders |
|---|---|
| 2024-01-01 | 2 |
| 2024-02-01 | 1 |
Premium share per month
Conditional agg inside buckets.
1SELECT DATE_TRUNC('month', created_at) AS m, COUNT(*) FILTER (WHERE amount > 100) AS premium FROM orders GROUP BY m;
| month | premium |
|---|---|
| 2024-01-01 | 1 |
| 2024-02-01 | 1 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.