DATE_TRUNC rounds a timestamp or date down to the specified unit—second through year.
DATE_TRUNC rounds a timestamp or date down to the specified time unit—second, minute, hour, day, week, month, quarter, or year—returning a new timestamp with lower-order fields zeroed.
Call DATE_TRUNC('unit', timestamp_expression). The unit must be a quoted string like 'day'. The function returns a TIMESTAMP without timezone.
Day, week, month, and year summarise metrics nicely for dashboards.Use month for revenue, week for active users, and day for operational alerts.
SELECT DATE_TRUNC('month', order_date) AS order_month, SUM(total_amount) AS revenue FROM Orders GROUP BY 1 ORDER BY 1;
SELECT DATE_TRUNC('month', o.order_date) AS month, p.name, SUM(oi.quantity * p.price) AS revenue FROM Orders o JOIN OrderItems oi ON oi.order_id = o.id JOIN Products p ON p.id = oi.product_id GROUP BY 1, 2 ORDER BY 1, 2;
Quote units, cast VARCHAR columns to TIMESTAMP first, and include DATE_TRUNC in GROUP BY to guarantee correct aggregation.Pre-compute for large tables if query speed matters.
Unquoted units raise errors: use 'month', not month. Truncating to 'hour' on a DATE adds midnight; cast to TIMESTAMP before calling. Forgetting GROUP BY with DATE_TRUNC causes aggregation mismatch.
DATE_TRUNC('week', timestamp) returns the previous Sunday at 00:00.
Yes.DATE_TRUNC('quarter', timestamp) returns the first day of the quarter at midnight.
Yes, it is IMMUTABLE in Redshift, so it always returns the same value for the same input.
.
Use DATE_TRUNC('week', timestamp_column); weeks start Sunday.
A function call prevents direct use of sort keys; create a derived column or materialized view for big tables.
No. Redshift supports up to 'year'; use EXTRACT((EXTRACT(year FROM ts)/10)::int)*10 for decades.