Skip to content

Dates and time

Truncate timestamps into days, weeks and months, filter by date ranges safely and do date arithmetic.

Practise: 15 questions

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:

  1. Choose the bucket. date_trunc('month', ts) snaps a timestamp down to the first moment of its month.
  2. Write the range with a closed start and an open end: >= start and < next_start.
  3. Group by the bucket, not the raw timestamp.
  4. 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

Variations

In other warehouses

Practise dates and time