Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Table orders(id, created_at timestamptz, total numeric). Write a PostgreSQL query that returns revenue per day for the last 30 days in the Europe/Berlin time zone, including days with no orders as 0.

Generate the 30 Berlin calendar days with generate_series, sum orders per Berlin day from a half-open created_at range that the index can use, and LEFT JOIN the days to those sums with COALESCE(..., 0) so empty days show 0. Compute today in Berlin explicitly with now() AT TIME ZONE 'Europe/Berlin' rather than relying on current_date, which follows the session's TimeZone setting.

Why this question is asked

Daily revenue charts are among the first queries anyone writes for a business, and they are also where time zone bugs hide: a dashboard that silently shifts an hour of sales into the wrong day, or a chart with missing days that looks like a flat line where there were zero orders. Interviewers ask it to see whether we fill gaps, bucket in the business's zone and keep the query index-friendly. In this answer, we will recap how timestamptz and AT TIME ZONE work, generate the days, bucket and join the orders, make the filter use an index, and look at date_trunc, date_bin and the session time zone trap.

1A Quick Recap of timestamptz and AT TIME ZONE

A timestamptz in PostgreSQL stores an absolute point in time, internally in UTC. It has no zone of its own; the session's TimeZone setting only controls how it is displayed. To ask which Berlin calendar day an order belongs to, we convert the point in time to Berlin wall clock time: created_at AT TIME ZONE 'Europe/Berlin' returns a timestamp without time zone, the local time in Berlin, and casting it to date gives the Berlin day.

The conversion works in the other direction too. A timestamp without time zone AT TIME ZONE 'Europe/Berlin' interprets that wall clock time as Berlin time and returns the matching timestamptz. We will use both directions, and they handle daylight saving time for us, so a Berlin day is 23 hours long in March and 25 in October.

2Generating Every Day, Even Days Without Orders

If we simply GROUP BY the order day, days with no orders do not appear at all, because there are no rows to group. A chart drawing those results joins the neighbours with a line and hides the zero. So we first produce the list of days ourselves.

SQL
WITH today AS (SELECT (now() AT TIME ZONE 'Europe/Berlin')::date AS t)
SELECT d::date AS day
FROM today, generate_series(t - 29, t, interval '1 day') AS d;
-- 2026-10-07, 2026-10-08, ..., 2026-11-05 (30 rows)

generate_series with a step interval returns timestamps, so we cast each one back to date. Notice that we compute today in Berlin explicitly. current_date would be the date in the session's time zone, which on a UTC server is still yesterday for the first one or two hours of every Berlin day.

3Bucketing and Joining the Orders

Now we total the orders per Berlin day and join the totals onto the days. The days table goes on the left of a LEFT JOIN so that every day survives, and COALESCE turns the NULL sum of an empty day into 0.

SQL
WITH today AS (
SELECT (now() AT TIME ZONE 'Europe/Berlin')::date AS t
), bounds AS (
SELECT (t - 29)::timestamp AT TIME ZONE 'Europe/Berlin' AS from_ts, -- Berlin midnight, 29 days ago
(t + 1)::timestamp AT TIME ZONE 'Europe/Berlin' AS to_ts -- Berlin midnight tomorrow
FROM today
), per_day AS (
SELECT (o.created_at AT TIME ZONE 'Europe/Berlin')::date AS day, SUM(o.total) AS revenue
FROM orders o, bounds b
WHERE o.created_at >= b.from_ts AND o.created_at < b.to_ts
GROUP BY 1
)
SELECT d::date AS day, COALESCE(p.revenue, 0) AS revenue
FROM today, generate_series(t - 29, t, interval '1 day') AS d
LEFT JOIN per_day p ON p.day = d::date
ORDER BY day;
-- 2026-11-03 | 1840.50
-- 2026-11-04 | 0 (no orders, still shown)
-- 2026-11-05 | 612.00
Step throughHow the query builds the report
  1. Compute today in Berlinnow() AT TIME ZONE 'Europe/Berlin'
  2. Turn Berlin midnights into timestamptz boundshalf-open range [from, to)
  3. Sum orders per Berlin day inside the rangeindex on created_at is used
  4. Generate all 30 days
  5. LEFT JOIN days to sumsCOALESCE(revenue, 0)

5 steps in order. Play them, or step through them one at a time.

The simpler version in many answers joins the raw orders directly with ON (o.created_at AT TIME ZONE 'Europe/Berlin')::date = d. It is correct, but there is a catch: because the condition wraps created_at in a function, PostgreSQL cannot use a plain index on created_at to find the last 30 days, and it may read far more of the table than needed. Pre-aggregating with a range filter avoids that.

4Why the Half-Open Range Uses the Index

A B-tree index on created_at stores the raw timestamptz values in order. The condition created_at >= from_ts AND created_at < to_ts compares the column itself with two constants, so PostgreSQL can jump to from_ts in the index and read until to_ts. That is what sargable means, short for search-argument-able.

The range is half-open, including the start and excluding the end, so that consecutive ranges never overlap or leave gaps, whatever the precision of the timestamps. A BETWEEN with an end of 23:59:59 would miss orders in the last fraction of a second. We compute the bounds in Berlin time, then convert them to timestamptz, so the range covers exactly 30 Berlin days, including the 25-hour day when clocks go back.

5Date_trunc, date_bin and the Session Time Zone

date_trunc('day', created_at AT TIME ZONE 'Europe/Berlin') is an equivalent way to bucket: it returns the Berlin midnight as a timestamp instead of a date. It shines when we change granularity, since 'week', 'month' or 'hour' are a parameter away. PostgreSQL 14 added date_bin, which buckets into arbitrary intervals from an origin, such as 15 minute slots.

SQL
SELECT date_bin(interval '15 minutes', created_at AT TIME ZONE 'Europe/Berlin',
timestamp '2026-01-01') AS slot, SUM(total)
FROM orders WHERE created_at >= now() - interval '1 day'
GROUP BY slot ORDER BY slot;
-- 2026-11-05 09:00:00 | 210.00
-- 2026-11-05 09:15:00 | 95.50

Finally, the trap the whole article circles around: current_date, ::date on a timestamptz and string literals without a zone all depend on the session TimeZone. Either set it explicitly for the reporting connection, SET TIME ZONE 'Europe/Berlin', or, as above, name the zone in every expression so the query gives the same answer from any client.

6Follow-up questions

How would you write the same in MySQL 8?

Generate the days with a recursive CTE, since MySQL has no generate_series: WITH RECURSIVE days AS (SELECT CURDATE() - INTERVAL 29 DAY AS d UNION ALL SELECT d + INTERVAL 1 DAY FROM days WHERE d < CURDATE()). Bucket with DATE(CONVERT_TZ(created_at, '+00:00', 'Europe/Berlin')) if created_at holds UTC values; named zones in CONVERT_TZ need the time zone tables loaded, otherwise it returns NULL. Then LEFT JOIN with COALESCE(SUM(total), 0). For the index, filter created_at with a half-open range computed in UTC. CURDATE() follows the session time_zone, so compute Berlin's today with CONVERT_TZ as well.

Why do we LEFT JOIN from the days and not from the orders?

The preserved side of a LEFT JOIN is the left one. Starting from the generated days keeps every day even when no order matches, while starting from orders would keep only days that have orders, which is exactly the gap we wanted to fill.

Would an expression index help instead?

Yes, an index on ((created_at AT TIME ZONE 'Europe/Berlin')::date) would make the function-wrapped join indexable, because AT TIME ZONE with a constant zone name is immutable. It only helps queries in that one zone, though, so a range on the raw column is the more general habit.

7Conclusion

In this answer, we converted orders to Berlin days with AT TIME ZONE, generated every one of the last 30 days with generate_series, summed orders per day inside a half-open created_at range that can use an index, and LEFT JOINed the days to the sums with COALESCE so empty days show 0. We also saw date_trunc and date_bin for other buckets, and why computing today in the business zone beats relying on the session's current_date.

What to say in the interviewAbout 90 seconds aloud

Open with

I would build it in three parts. First, today in Berlin: now() AT TIME ZONE 'Europe/Berlin' cast to date, because current_date follows the session time zone and on a UTC server it is yesterday for the first hours of the Berlin day.

Then, if they want more

Second, I generate the 30 days with generate_series from today minus 29 to today, step one day, cast to date, because a plain GROUP BY never returns days without orders. Third, I aggregate orders per Berlin day, using created_at AT TIME ZONE 'Europe/Berlin' cast to date as the bucket.

For the filter I use a half-open range on the raw column, created_at greater or equal to Berlin midnight 29 days ago and less than Berlin midnight tomorrow, both computed as a local timestamp AT TIME ZONE 'Europe/Berlin'.

That keeps the condition sargable, so the index on created_at is used, and it covers exact Berlin days even across daylight saving changes.

Then I LEFT JOIN the generated days to the daily sums and select COALESCE of the sum and zero, ordered by day. date_trunc on the Berlin timestamp is an alternative bucket that switches easily to weeks or months, and date_bin since PostgreSQL 14 buckets into arbitrary slots like 15 minutes.

I would also set the session time zone or name it everywhere, so results do not change with the client.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Table orders(id, created_at timestamptz, total numeric). Write a PostgreSQL query that...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/6cdbd5d480/