Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a query that reports monthly revenue for 2025 from orders(total numeric, created_at timestamptz) in the Europe/Berlin time zone, with months that have no orders shown as 0.

We generate the twelve months of 2025 with generate_series, aggregate orders per Berlin month with date_trunc('month', created_at AT TIME ZONE 'Europe/Berlin'), LEFT JOIN the aggregates to the months, and show COALESCE(revenue, 0). The orders are filtered with a half-open range of Berlin local midnights converted to timestamptz, so the filter stays index-friendly. In MySQL we build the months with a recursive CTE or calendar table and convert with CONVERT_TZ, which needs the time zone tables loaded.

Why this question is asked

Monthly revenue sounds like the simplest report there is, and it is wrong surprisingly often. If months are cut at UTC midnight, the orders from the first hour or two of each Berlin month land in the previous month, and a month without orders simply disappears from the chart instead of showing zero. Interviewers ask this because it combines three ideas that real reports need: time zone conversion, filling gaps with a generated series, and keeping the filter fast. In this answer, we will recap how PostgreSQL stores timestamptz, build the query step by step, see why each part is there, and then write the MySQL version.

1A Quick Recap of timestamptz and AT TIME ZONE

A timestamptz column in PostgreSQL stores an absolute instant, internally in UTC. It does not remember the zone it was written in; it is displayed in the session's time zone setting. So an order placed at 00:30 on 1 March in Berlin is stored as 23:30 on 28 February UTC.

AT TIME ZONE converts in both directions, and the direction depends on the input type. timestamptz AT TIME ZONE 'Europe/Berlin' gives a plain timestamp, the wall-clock time in Berlin. timestamp AT TIME ZONE 'Europe/Berlin' does the opposite: it reads a wall-clock time as Berlin time and gives back the instant as timestamptz. Using a zone name rather than a fixed offset such as +01 matters, because Berlin switches between +01 in winter and +02 in summer.

SQL
SELECT TIMESTAMPTZ '2025-02-28 23:30:00+00' AT TIME ZONE 'Europe/Berlin';
-- 2025-03-01 00:30:00 Berlin wall-clock time: already March
SELECT TIMESTAMP '2025-01-01 00:00' AT TIME ZONE 'Europe/Berlin';
-- 2024-12-31 23:00:00+00 the instant when 2025 began in Berlin

2Writing the Query

Here is the full query for orders(total numeric, created_at timestamptz).

SQL
WITH months AS (
SELECT generate_series(DATE '2025-01-01', DATE '2025-12-01', INTERVAL '1 month')::date AS month
),
revenue AS (
SELECT date_trunc('month', created_at AT TIME ZONE 'Europe/Berlin')::date AS month,
SUM(total) AS revenue
FROM orders
WHERE created_at >= TIMESTAMP '2025-01-01 00:00' AT TIME ZONE 'Europe/Berlin'
AND created_at < TIMESTAMP '2026-01-01 00:00' AT TIME ZONE 'Europe/Berlin'
GROUP BY 1
)
SELECT m.month, COALESCE(r.revenue, 0) AS revenue
FROM months m
LEFT JOIN revenue r ON r.month = m.month
ORDER BY m.month;
-- 2025-01-01 | 18250.40
-- 2025-02-01 | 16110.00
-- 2025-03-01 | 0 no orders in March (shop closed for a migration)
-- ...
-- 2025-12-01 | 30402.75 12 rows, always
Step throughHow the report is built
  1. Generate 12 month startsgenerate_series, 2025-01-01 to 2025-12-01
  2. Filter orders to 2025 in Berlinhalf-open range on created_at, index-friendly
  3. Group by Berlin monthdate_trunc on Berlin wall-clock time
  4. LEFT JOIN months to revenuemonths without orders get NULL
  5. COALESCE(revenue, 0)NULL becomes 0

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

The query has three parts, and each solves one problem. We look at them in turn.

3Grouping by the Berlin Month

date_trunc('month', ...) cuts a timestamp down to the first moment of its month. If we applied it to created_at directly, it would cut at month boundaries in the session time zone, which on most servers is UTC. That puts an order from 00:30 on 1 March Berlin time into February. Converting first with AT TIME ZONE 'Europe/Berlin' gives the Berlin wall-clock time, so the cut happens at Berlin midnight. Casting the result to date gives clean values like 2025-03-01 that match the generated months.

PostgreSQL 12 and later also accept a third argument, date_trunc('month', created_at, 'Europe/Berlin'), which truncates in that zone and returns a timestamptz. Either form works, as long as both sides of the join use the same representation.

4Keeping the Filter Sargable

A condition is sargable when the database can use an index to evaluate it, which mostly means the indexed column stands alone on one side of the comparison. A filter like WHERE date_part('year', created_at AT TIME ZONE 'Europe/Berlin') = 2025 is correct, but it computes an expression for every row, so an index on created_at cannot help and the whole table is read.

Instead, we convert the boundaries, not the column. TIMESTAMP '2025-01-01 00:00' AT TIME ZONE 'Europe/Berlin' is the exact instant when 2025 began in Berlin, 23:00 UTC on 31 December 2024, and the same for 2026. The range is half-open, greater than or equal to the start and strictly less than the end, so an order at exactly midnight on 1 January 2026 is not counted twice and we never need a fragile end value like 23:59:59.999. With an index on orders(created_at), the database reads only 2025's rows.

5Filling Empty Months With Zero

GROUP BY only creates groups for months that have orders, so March in our example would be missing from the aggregated result, and a chart would draw a straight line from February to April. generate_series produces all twelve month starts, and the LEFT JOIN keeps every one of them, giving NULL revenue for months without a match. COALESCE(r.revenue, 0) turns that NULL into 0.

Aggregating first and joining second keeps the join small, twelve rows against at most twelve. The alternative, LEFT JOIN orders to months and then COALESCE(SUM(o.total), 0), is also correct, as long as the date condition is in the ON clause and not in WHERE, which would remove the empty months again.

6The MySQL Version

MySQL has no generate_series, so we build the months with a recursive CTE, or better, join to a permanent calendar table. MySQL TIMESTAMP columns store UTC internally, and CONVERT_TZ converts between zones. Named zones such as 'Europe/Berlin' work only if the time zone tables are loaded, with mysql_tzinfo_to_sql on Linux; otherwise CONVERT_TZ returns NULL and every order silently drops out of the report.

SQL
WITH RECURSIVE months AS (
SELECT DATE '2025-01-01' AS month
UNION ALL
SELECT month + INTERVAL 1 MONTH FROM months WHERE month < DATE '2025-12-01'
),
revenue AS (
SELECT DATE_FORMAT(CONVERT_TZ(created_at, '+00:00', 'Europe/Berlin'), '%Y-%m-01') AS month,
SUM(total) AS revenue
FROM orders
WHERE created_at >= CONVERT_TZ('2025-01-01 00:00:00', 'Europe/Berlin', '+00:00')
AND created_at < CONVERT_TZ('2026-01-01 00:00:00', 'Europe/Berlin', '+00:00')
GROUP BY 1
)
SELECT m.month, COALESCE(r.revenue, 0) AS revenue
FROM months m LEFT JOIN revenue r ON r.month = m.month
ORDER BY m.month; -- 12 rows; assumes the session time_zone is '+00:00'

The CONVERT_TZ calls with the literal boundaries are computed once, so the filter still uses an index on created_at, just as in the PostgreSQL version. Because a TIMESTAMP is shown in the session time zone, the query assumes the session runs with time_zone set to UTC; setting it explicitly in the connection removes that assumption.

7Follow-up questions

Why not set the session time zone to Europe/Berlin and group by date_trunc directly?

It works in PostgreSQL, because date_trunc on timestamptz uses the session zone. But the result then depends on a connection setting that someone else may change, and a connection pool may hand out sessions configured differently. An explicit AT TIME ZONE in the query makes the report self-contained.

What if total is stored with a currency per order?

Then summing totals across currencies is meaningless. We either group by currency as well, or convert each order to the reporting currency using the rate valid at the order date, from a rates table joined on currency and date.

How does daylight saving time affect this report?

Not at all when we use a named zone, because PostgreSQL applies the correct offset for each instant. With a fixed offset like +01, every order between the last Sunday of March and the last Sunday of October would be shifted by an hour, and month edges in summer would be wrong.

8Conclusion

In this answer, we built a monthly revenue report in Berlin time. We grouped by date_trunc on created_at AT TIME ZONE 'Europe/Berlin' so months begin at Berlin midnight, generated all twelve months with generate_series and LEFT JOINed the aggregates so empty months appear, and showed them as 0 with COALESCE. We filtered with a half-open range whose Berlin boundaries are converted to instants, which keeps the predicate sargable, and in MySQL we used a recursive CTE and CONVERT_TZ, which needs the time zone tables loaded.

What to say in the interviewAbout 90 seconds aloud

Open with

The two traps are month boundaries and missing months. created_at is a timestamptz, so it is an absolute instant stored in UTC, and if I truncate it to the month directly, the boundaries fall at UTC midnight, which puts the first hour or two of each Berlin month into the previous month.

Then, if they want more

So I group by date_trunc of 'month' on created_at AT TIME ZONE 'Europe/Berlin', which gives the Berlin wall-clock time, and cast that to a date.

For missing months, GROUP BY only returns months that have orders, so I generate the twelve month starts with generate_series from 2025-01-01 to 2025-12-01 by one month, LEFT JOIN the aggregated revenue to that, and wrap it in COALESCE with 0. For the filter I do not apply a function to created_at, because that would stop the index being used.

Instead I convert the boundaries: Berlin midnight on 1 January 2025 and 1 January 2026, each as a timestamp AT TIME ZONE 'Europe/Berlin', with greater-or-equal the start and strictly less than the end. That is half-open, so nothing is counted twice, and an index on created_at serves it.

I always use the zone name rather than a fixed offset, because of daylight saving time. In MySQL I would use a recursive CTE or a calendar table for the months and CONVERT_TZ, making sure the time zone tables are loaded, since otherwise CONVERT_TZ returns NULL.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 12
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 "Write a query that reports monthly revenue for 2025 from orders(total numeric...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/f5f7c746c6/