date-time

DATE_TRUNC

Rounds a timestamp down to the beginning of the specified unit (year, month, week, day, hour, etc.). Native to Postgres; MySQL uses DATE_FORMAT or manual arithmetic.

DATE_TRUNC('unit', timestamp)

Parameters / Modifiers

Parameter Purpose
'year' | 'quarter' | 'month' | 'week' | 'day' | 'hour' | 'minute' Truncation granularity
AT TIME ZONE 'zone' Truncate in a specific timezone before returning UTC
DATE_FORMAT(dt, fmt) MySQL fallback used to emulate DATE_TRUNC via format strings

Examples

SELECT DATE_TRUNC('month', NOW());

Postgres: first instant of the current month

SELECT DATE_TRUNC('day', created_at), COUNT(*) FROM events GROUP BY 1;

Daily event totals bucketed by day

SELECT DATE_FORMAT(created_at, '%Y-%m-01') FROM events;

MySQL equivalent for month truncation, returned as a date string

SELECT DATE_TRUNC('hour', ts AT TIME ZONE 'Asia/Kolkata') FROM logs;

Truncate to hour boundaries in IST rather than UTC

Dialect notes / Gotcha

Postgres-only function — MySQL/SQLite require DATE_FORMAT or strftime. Weeks start on Monday in Postgres (ISO), which may differ from application definitions.

Related functions

← All SQL functions · SQL cheat sheet · Window functions · PostgreSQL cheat sheet