Video in progress

How do you count orders per day, and how does the time zone affect the result on a `timestamptz` column?

You group by date_trunc('day', ...) or ::date, but for timestamptz the "day" is cut according to the session's TimeZone setting. To get the exact business day, I write AT TIME ZONE 'Asia/Tashkent'.

📖 Answer

The simple version:

SELECT date_trunc('day', created_at) AS day, count(*)
FROM orders
WHERE created_at >= now() - interval '30 days'
GROUP BY 1
ORDER BY 1;

The trap is that if the server's or connection's TimeZone is UTC, an order placed at 21:00 in Tashkent in the evening (16:00 UTC) lands on the right day, but one placed at 03:00 in the morning (22:00 UTC the previous day) gets recorded on yesterday. The report then doesn't match the accounting numbers.

The explicit version:

SELECT (created_at AT TIME ZONE 'Asia/Tashkent')::date AS day,
       count(*)
FROM orders
GROUP BY 1
ORDER BY 1;

timestamptz AT TIME ZONE 'zone' returns the "wall clock" time in that zone as a timestamp, and then we take the date from it.

There are also the empty days: a day with no orders doesn't appear in the result at all. For a chart, I build the list of days with generate_series and LEFT JOIN onto it.