Explain how DATE_TRUNC and time bucketing work, and how you would bucket events to week or month for time-series aggregation.

Last updated 13 July 2026

DATE_TRUNC snaps a timestamp down to the start of a given unit (e.g. the first instant of its week or month), so all timestamps in the same period collapse to one bucket label you can GROUP BY. Time bucketing is just grouping rows by that truncated value.

  • How it works: DATE_TRUNC('month', ts) turns 2024-03-17 into 2024-03-01; 'week' returns the week's starting Monday (in Postgres).

  • Bucket then aggregate: Put the truncated value in both SELECT and GROUP BY, then apply COUNT/SUM/AVG.

  • Watch the edges:

    • Week start day and timezone matter: truncate in the correct tz or convert first, since UTC vs. local shifts which day/week a row lands in.

    • Fixed-width buckets (e.g. 15 min, 5 day) need date_bin (Postgres) or TIME_BUCKET (TimescaleDB); DATE_TRUNC only does calendar units.

  • Empty buckets: DATE_TRUNC only emits periods that have rows; join against a generated calendar/date spine to show zero-count periods.

[lang:sql] SELECT DATE_TRUNC('week', event_ts) AS wk, COUNT(*) AS events FROM events GROUP BY 1 ORDER BY 1;

  • https://sqlmaxx.com/learn-sql/grouping-by-date/
  • https://mode.com/blog/date-trunc-sql-timestamp-function-count-on/
  • https://alexanderobregon.substack.com/p/group-records-by-week-or-month-in
  • https://sqlpad.io/tutorial/sql-date-timestamp-interview-questions/
  • https://docs.snowflake.com/pt/user-guide/querying-time-series-data
  • https://dev.to/gowthampotureddi/meta-data-engineering-interview-questions-top-topics-problems-solutions-304g
  • https://dev.to/gowthampotureddi/salesforce-data-engineering-interview-questions-5bo9
  • https://medium.com/@Rohan_Dutt/10-advanced-time-series-transformations-in-sql-youve-probably-never-used-33c1322756d5
All Advanced SQL interview questions