When you need it
"Orders per month", "signups last week", "days between order and delivery", "everything in Q1", "by day of week". Words that signal it: "per day", "monthly", "last 30 days", "between", "since", "age", "how long".
Two jobs: turn a timestamp into a bucket (day, week, month), and select the right range of time.
The shape of the query
select date_trunc('month', ts)::date as month, count(*) as n
from t
where ts >= date '2025-01-01'
and ts < date '2025-04-01'
group by 1
order by 1;Step by step:
- Choose the bucket.
date_trunc('month', ts)snaps a timestamp down to the first moment of its month. - Write the range with a closed start and an open end:
>= start and < next_start. - Group by the bucket, not the raw timestamp.
- Sort by the bucket so the output reads as a timeline.
select date_trunc('month', ordered_at)::date as month,
count(*) as orders,
count(distinct customer_id) as customers
from orders
where status = 'completed'
and ordered_at >= date '2024-01-01'
and ordered_at < date '2025-01-01'
group by 1
order by 1;Date arithmetic and parts:
select ticket_id,
created_at::date as opened_day,
extract(isodow from created_at) as weekday_1_is_monday,
round(extract(epoch from (first_response_at - created_at)) / 3600.0, 1) as hours_to_first_reply
from tickets
where first_response_at is not null
order by ticket_id
limit 10;Traps interviewers look for
BETWEENon timestamps.between '2025-01-01' and '2025-01-31'stops at midnight on the 31st, so almost all of that day is lost. Use>= start and < day after the end.- Time zones. A timestamp stored in UTC can fall on a different calendar day for the business. If the prompt names a zone, convert before truncating. If it does not, say that you assumed UTC.
- Grouping by the raw timestamp. Each row becomes its own group. Truncate or cast to
datefirst. - Month lengths. "Last 30 days" and "last month" are different questions. Adding
interval '1 month'to January 31 does not land where you expect. Preferdate_truncplus a fixed offset. - Week definitions.
date_trunc('week', ...)starts on Monday in PostgreSQL. Other engines or a US report may start on Sunday. State which one you use. - Using the clock in a screen.
now()andcurrent_datemake answers change daily. If the prompt gives a reference date, use it. Otherwise anchor on the maximum date in the data. - Empty periods. A month with no rows does not appear. If the chart needs a zero, join to a calendar of months.
Variations
- Age and duration. Subtract two dates for days (
d2 - d1), or timestamps for an interval you convert withextract(epoch from ...). - Day of week and hour.
extract(dow from ts)orextract(hour from ts)to find peak times. - Rolling windows. "Last 7 days from each date" is a self-join or a window frame. See running totals.
- Fiscal calendars. Shift the date first:
date_trunc('quarter', d + interval '3 months'). - Age at event.
age(event_date, birth_date)in PostgreSQL, or a difference in days divided by 365.25 for an approximate year count.
In other warehouses
DATE_TRUNCargument order differs. PostgreSQL, Snowflake, Redshift and Databricks usedate_trunc('month', ts). BigQuery reverses it:DATE_TRUNC(d, MONTH), and usesTIMESTAMP_TRUNC(ts, MONTH)for timestamps.- SQL Server gained
DATETRUNC(month, ts)in SQL Server 2022. Before that, useDATEFROMPARTS(YEAR(d), MONTH(d), 1). - Date differences. Snowflake, SQL Server and Redshift use
DATEDIFF(day, start, end). BigQuery usesDATE_DIFF(end, start, DAY). PostgreSQL just subtracts. - Casting.
::dateis PostgreSQL and Snowflake. The portable form isCAST(ts AS DATE).