SQL DATE_TRUNC

Rounds a date or timestamp DOWN to the start of a specified unit — the exact opposite job from EXTRACT, which pulls a piece OUT.

What & Why

DATE_TRUNC('unit', source) rounds a timestamp down to the beginning of whatever unit you specify — truncating to 'month' zeroes out the day and time, landing on the 1st of that month at midnight. This is genuinely different from EXTRACT: EXTRACT pulls one number out and discards everything else; DATE_TRUNC keeps a full date/timestamp value, just rounded down.

See How It Works

BUSINESS QUESTION

Marketing wants each lead timestamp rounded down to its year, month, and day boundaries.

idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
Watch the same timestamps truncate at three levelsStep 1 of 3
DATE_TRUNC('year', created_at)::date
idcreated_atsignup_year
3012024-01-21 09:10:00+002024-01-01
3022024-01-24 12:40:00+002024-01-01
3032024-02-16 08:30:00+002024-01-01
3042024-03-20 17:15:00+002024-01-01

Year truncation moves every displayed 2024 timestamp to the first day of the year.

EXAMPLE QUERY
SELECT
  id,
  created_at,
  DATE_TRUNC('year', created_at)::date AS signup_year,
  DATE_TRUNC('month', created_at)::date AS signup_month,
  DATE_TRUNC('day', created_at)::date AS signup_day
FROM marketing.leads
ORDER BY created_at, id;
Now You Try

Practice this concept

Marketing wants each lead timestamp rounded down to its year, month, and day boundaries.

Available schema
marketing

Prefix tables with marketing.table_name.

idcreated_atsignup_yearsignup_monthsignup_day
marketing.leads
ColumnType
idinteger
campaign_idinteger
emailtext
created_attimestamp with time zone
qualified_attimestamp with time zone
converted_attimestamp with time zone
lead_scoreinteger
sourcetext
countrytext
archive_statustext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario