date_trunc() shortens a Date or DateTime value to the start of a specified time unit (minute, hour, day, week, month, quarter, or year).
Aggregate queries often need timestamps aligned to consistent boundaries. date_trunc() snaps any Date/DateTime to the opening tick of a unit so group by clauses work reliably.
date_trunc('unit'
, timestamp_expression
[, 'timezone'
]) → DateTime/Date.
Supported units: second, minute, hour, day, week, month, quarter, year.
Use date_trunc('day', order_date)
so all orders on the same calendar day share one key.
Add the optional third parameter: date_trunc('hour', created_at, 'UTC')
. This prevents double-counting when users span zones.
For 15-minute buckets, combine toStartOfInterval
: toStartOfInterval(order_date, INTERVAL 15 minute)
. It returns the nearest lower 15-minute mark.
GROUP BY date_trunc('month', order_date)
aggregates all same-month rows, even across years.
Store timestamps in UTC, truncate in UTC, then convert for display. Index the raw DateTime column; the function will still leverage partition pruning if partitions are also UTC-aligned.
Truncating before applying filters can broaden the time range. Always filter first, then group. Avoid string-to-date casts inside date_trunc(); cast once in a CTE.
Yes. When the source is Date, units below ‘day’ return midnight of that day.
Yes. Given the same timestamp, unit, and timezone, it will always return the same value.
Use toStartOfInterval(col, INTERVAL 5 minute)
for custom sizes.