DATE_TRUNC() rounds or cuts a timestamp down to the specified unit (second-to-millennium), letting you ignore lower-precision parts like hours or minutes.
DATE_TRUNC() returns the input timestamp with all fields smaller than the requested unit set to their minimal values. Use it to strip the time from a timestamp, round to the nearest hour, or group data into calendar buckets.
Select date_trunc('day', order_date)
. The function zeroes hours, minutes, and seconds, so 2024-05-15 13:42:10
becomes 2024-05-15 00:00:00
. Cast to DATE
if you need a pure date.
Put the unit first, then the timestamp expression. Valid units include microsecond, millisecond, second, minute, hour, day, week, month, quarter, year, decade, century, millennium.
DATE_TRUNC ( 'unit', timestamp_expression )
unit – text literal specifying the precision. timestamp_expression – any TIMESTAMP
, TIMESTAMPTZ
, or INTERVAL
value.
The query rounds order dates to midnight, groups by customer and day, and sums revenue.
SELECT c.id, c.name,
DATE_TRUNC('day', o.order_date) AS order_day,
SUM(o.total_amount) AS daily_sales
FROM Customers c
JOIN Orders o ON o.customer_id = c.id
GROUP BY c.id, c.name, order_day
ORDER BY order_day, c.id;
Use DATE_TRUNC() whenever you need flexible granularities (hour, week, month) or want to keep a timestamp data type. CAST() only converts to DATE
, losing sub-day context.
Passing 'hours'
or 'mins'
raises invalid input syntax. Use the singular form: 'hour'
, 'minute'
.
DATE_TRUNC() expects a timestamp or interval. Cast the DATE
column to TIMESTAMP
or skip truncation altogether.
Truncate in a derived table so indexes on the raw timestamp remain usable. For example, use a CTE, then group on the truncated result.
DATE()
casts to date; DATE_PART()
extracts a single field; TO_CHAR()
formats timestamps for display.
Not directly. Truncating in the WHERE clause prevents index use. Truncate in a subquery or materialized view, then filter.
Yes. Pass 'quarter'
as the unit: date_trunc('quarter', order_date)
.
DATE_TRUNC() returns a modified timestamp. DATE_PART() extracts one numeric field (e.g., month = 5).