Learn SQL
-- aggregations.date_trunc_grouping

Time Bucketing: DATE_TRUNC GROUP BY in SQL

Monthly rollups, 7-day windows, half-open buckets

--concept

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.

--how it works
1

Truncate to bucket

DATE_TRUNC(month, ts) collapses to month starts for GROUP BY.

2

Range half-open inside

Day filters stay >= start AND < next — timestamp-safe.

3

Pivot per bucket

FILTER/COUNT per bucket in one scan — no N queries.

4

Zone on display

UTC storage; AT TIME ZONE converts. Index expression or range raw.

--visualization
DATE_TRUNC(month) → GROUP BY month — same scan pivots premium via FILTER
monthorders
2024-01-012
2024-02-011
Stage 1 / 1
Half-open days inside; UTC store, zone on display.
--example
query.sql
1SELECT DATE_TRUNC('month', created_at) AS m, COUNT(*) AS orders FROM orders GROUP BY m ORDER BY m;
Result
monthorders
2024-01-012
2024-02-011

Timestamps collapse to month starts, then group. Same shape with FILTER splits premium vs standard per month in one scan — no N queries.

--variants

Monthly order counts

Two buckets from three rows.

query.sql
1SELECT DATE_TRUNC('month', created_at) AS m, COUNT(*) AS orders FROM orders GROUP BY m ORDER BY m;
Result
monthorders
2024-01-012
2024-02-011
1Truncate maps Jan-15/31 both to Jan-01.
2GROUP BY month starts.
3ORDER BY month chronological.

Premium share per month

Conditional agg inside buckets.

query.sql
1SELECT DATE_TRUNC('month', created_at) AS m, COUNT(*) FILTER (WHERE amount > 100) AS premium FROM orders GROUP BY m;
Result
monthpremium
2024-01-011
2024-02-011
1Each bucket tallies its premium slice.
2One scan, pivoted columns.
3CASE fallback where FILTER unsupported.
--key facts
DATE_TRUNCbucket then group — cohorts
Half-open daystimestamp-safe ranges
UTC storeconvert on display
--use cases
Revenue cohorts + funnel-by-month
Retention buckets + 7-day rollups
--under the hood
DATE_TRUNC grouping sorts by bucket — BRIN/B-tree on ts feeds ordered scans on huge time tables.
Continuous aggregates (Timescale) maintain these buckets incrementally.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.