Learn SQL/Intermediate/Date & Time/SQL DATE_TRUNC by Week

SQL DATE_TRUNC by Week

Rounds down to the Monday of the current week — Postgres's weeks always start on Monday for this purpose, following the ISO standard.

What & Why

DATE_TRUNC('week', date_column) rounds down to the Monday that starts the containing ISO week.

See How It Works

BUSINESS QUESTION

Growth wants weekly event totals.

iduser_idevent_namecreated_atproperties
1001101signup2024-01-15 09:12:00+00{"source":"organic"}
1002101activated2024-01-16 14:25:00+00{"step":"workspace"}
1003102signup2024-02-10 11:08:00+00{"source":"paid"}
1004103report_viewed2024-03-12 16:40:00+00{"report":"retention"}
EXAMPLE QUERY
SELECT
  DATE_TRUNC('week', created_at)::date AS event_week,
  COUNT(*) AS events
FROM growth.events
GROUP BY event_week
ORDER BY event_week;
RESULT — exact output from the displayed Queryflo rows
event_weekevents
2024-01-152
2024-02-051
2024-03-111

PostgreSQL truncates weeks to Monday boundaries.

Now You Try

Practice this concept

Growth wants weekly event totals.

Available schema
growth

Prefix tables with growth.table_name.

event_weekevents
growth.events
ColumnType
idbigint
user_idinteger
event_nametext
created_attimestamp with time zone
propertiesjsonb
deprecated_metrictext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario