DATE_TRUNC shortens a timestamp or interval to a chosen precision (year, month, day, etc.) so you can group or filter data at that level.
DATE_TRUNC lets you drop the lower-order time fields—hours, minutes, seconds—so records that share the same day, month, or year line up. This is essential for quick GROUP BY queries and calendar-based reports.
Use DATE_TRUNC(text precision, timestamp source)
. Precision is a quoted string like 'day'
, 'month'
, 'quarter'
, or 'week'
. The source can be a column, literal, or expression.
Wrap order_date
with DATE_TRUNC('month', order_date)
and GROUP BY the result. All orders from June 2024 share the same truncated timestamp 2024-06-01 00:00
.
PostgreSQL supports year
, quarter
, month
, week
, day
, hour
, minute
, and second
. For fiscal calendars, truncate first and then add offsets (e.g., + '-1 month'::interval
).
Always alias the truncated column (AS month_start
) for readability. Index the raw timestamp; PostgreSQL can still use the index when you call DATE_TRUNC in GROUP BY.
Passing an unquoted precision string or using TRUNC()
instead of DATE_TRUNC()
both raise errors. Cast your columns to timestamp
when working with date
types.
Yes, but PostgreSQL implicitly casts DATE to TIMESTAMP at midnight. You can cast explicitly with order_date::timestamp
for clarity.
Yes. PostgreSQL can use a b-tree index on the raw timestamp when DATE_TRUNC appears in the GROUP BY or WHERE clause.
Truncate to 'year'
first, then add or subtract an interval offset that matches your fiscal calendar.