Dates, Times and Text in SQL

Truncating and bucketing dates, handling time zones, building calendars, and cleaning text inside queries.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Aggregation with GROUP BY and HAVING

Almost every analysis groups by time, and date logic is where subtle bugs hide.

Dates

  • Truncate to periods: DATE_TRUNC('month', created_at) (PostgreSQL, Snowflake), DATE_TRUNC(created_at, MONTH) (BigQuery).
  • Extract parts: EXTRACT(DOW FROM ts), year, hour.
  • Arithmetic: created_at + INTERVAL '7 days', DATE_DIFF, AGE.
  • Casting: turn strings to dates with CAST or TO_DATE, and timestamps to dates when you only need the day.

Time zones

Timestamps are often stored in UTC. A "day" for a business in India or California starts at a different UTC hour. Convert before truncating, or daily totals shift across midnight.

Gaps in time series

If no orders happened on a day, GROUP BY simply skips it and charts connect the gap misleadingly. Generate a date spine (generate_series in PostgreSQL, GENERATE_DATE_ARRAY in BigQuery, or a calendar table) and LEFT JOIN your data onto it.

Inclusive vs exclusive ranges

Prefer created_at >= '2024-03-01' AND created_at < '2024-04-01' over BETWEEN with timestamps, which misses events after midnight on the last day.

Text

LOWER, TRIM, REPLACE, SUBSTRING, SPLIT_PART, CONCAT, LIKE/ILIKE, and regular expression functions for extracting patterns such as UTM parameters from URLs.

Pitfall: mixing dialect syntax; keep your warehouse's function reference open. Move on when you can produce a gap-free daily series in the correct local time zone.

Key concepts

  • DATE_TRUNC and EXTRACT
  • Date arithmetic and intervals
  • Time zones and UTC
  • Date spines and calendar tables
  • Half-open date ranges
  • String functions
  • Regular expressions in SQL

Mini project

Using NYC taxi trip data (available as a BigQuery public dataset), compute trips per local hour of day and per weekday for one month, with a date spine so no hour is missing.

Check yourself

Why can BETWEEN '2024-03-01' AND '2024-03-31' undercount events stored as timestamps?

Free resources