Quick revision
The short answer
We filter 2025 with a half-open range in WHERE, group by customer_id, and compute the three numbers with conditional aggregation: COUNT(*) for all orders, COUNT(*) FILTER (WHERE status = 'CANCELLED') for cancelled ones, and SUM(total) FILTER (WHERE status <> 'CANCELLED') for the amount spent, or the portable CASE forms. HAVING then keeps only customers whose non-cancelled spend is over 1000, and COALESCE turns a NULL sum into 0 where we need a number.
What to remember
In this answer, we built the report with a half-open date range in WHERE, GROUP BY customer_id, COUNT(*) for all orders and conditional aggregation for cancelled orders and non-cancelled spend, using either CASE expressions or PostgreSQL's FILTER clause. HAVING filters the groups after aggregation because WHERE runs before any sum exists, and SUM over no matching rows returns NULL, which COALESCE turns into 0 when we need a number.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We filter 2025 with a half-open range in WHERE, group by customer_id, and compute the three numbers with conditional aggregation: COUNT(*) for all orders, COUNT(*) FILTER (WHERE status = 'CANCELLED') for cancelled ones, and SUM(total) FILTER (WHERE status <> 'CANCELLED') for the amount spent, or the portable CASE forms. HAVING then keeps only customers whose non-cancelled spend is over 1000, and COALESCE turns a NULL sum into 0 where we need a number.
Why this question is asked
Reports such as this one are everyday work: per customer, per product or per region, count some things, sum others, and keep only the interesting groups. Interviewers like it because one query exercises several ideas at once: filtering before grouping, conditional aggregation, the difference between WHERE and HAVING, and the NULL that SUM returns over nothing. In this answer, we will recap how GROUP BY works, build the query in steps, write it portably and with PostgreSQL's FILTER clause, look at the NULL edge case, and finish with indexing.
1A Quick Recap of GROUP BY and Aggregates
GROUP BY collapses rows that share the same value in the grouping columns into one output row per group. Aggregate functions such as COUNT, SUM and MAX then compute one value for each group. The order of evaluation matters: the database first applies WHERE to individual rows, then forms groups, then computes aggregates, and only then applies HAVING to whole groups. So WHERE decides which rows enter the groups, and HAVING decides which groups leave.
- FROM ordersall rows
- WHERE created_at in 2025rows filtered one by one
- GROUP BY customer_idone group per customer
- Compute aggregatescounts and sums per group
- HAVING spent > 1000groups filtered
- SELECT and ORDER BYshape the output
6 steps in order. Play them, or step through them one at a time.
2Building the Query Step by Step
We start with the date filter. The cleanest way to say in 2025 is a half-open range: on or after 1 January 2025 and strictly before 1 January 2026. It includes every instant of 31 December, needs no 23:59:59.999 tricks, and leaves created_at bare so an index on it can be used.
The idea behind the two CASE expressions is called conditional aggregation. Every row of the group enters both sums, but each CASE decides what that row contributes. For cancelled_orders, a cancelled row contributes 1 and any other row 0, so the sum is a count. For spent, a non-cancelled row contributes its total, and a cancelled row contributes nothing: CASE without an ELSE returns NULL, and SUM ignores NULLs. This version runs unchanged on PostgreSQL, MySQL and most other engines.
Note that if created_at is a timestamptz, the literal '2025-01-01' is interpreted in the session's time zone. For a company that reports in UTC, we would write '2025-01-01 00:00:00+00' to be explicit.
3The Same Query With FILTER in PostgreSQL
PostgreSQL supports the standard FILTER clause, which says the same thing more directly: apply this aggregate only to the rows matching the condition.
I prefer FILTER when the code only has to run on PostgreSQL, because it reads like the requirement. MySQL 8.4 does not support FILTER, so for portable code the CASE form is the one to use.
4Why HAVING and Not WHERE
It is tempting to move the spend condition into WHERE, but WHERE runs before grouping, row by row, and at that point there is no sum yet. Writing WHERE SUM(total) > 1000 is an error: aggregate functions are not allowed in WHERE. And writing WHERE total > 1000 means something different: it keeps only individual orders over 1000, so a customer with three orders of 400 would vanish completely, even though their total spend is 1200.
So the rule is simple: conditions about single rows belong in WHERE, where they also reduce the work, and conditions about aggregates belong in HAVING.
5The NULL That SUM Returns Over Nothing
Consider a customer whose only orders in 2025 were all cancelled. COUNT(*) gives 3, the cancelled count gives 3, and SUM over the non-cancelled rows has no values at all, so it returns NULL, not 0. That is how SQL defines SUM of an empty set. In our query, HAVING NULL > 1000 is UNKNOWN, so the customer is dropped anyway, which is what we want. But if we removed the HAVING or wanted to show all customers, the spent column would show NULL, and a Java mapping to a primitive or a dashboard that adds the column up could fail or mislead.
COUNT is different: COUNT(*) and COUNT(col) return 0 for no rows, never NULL. In Java we would read spent as a BigDecimal, which can hold the exact numeric value and can be null, rather than a double, which would lose precision for money.
6Making It Fast
For one year of data in a large table, an index on (created_at) lets the database read only 2025. If the report runs often, a covering index on (created_at, customer_id, status, total) lets PostgreSQL answer from the index alone with an index-only scan, when the visibility map is up to date. The grouping then runs as a hash aggregate over the matching rows. I would check with EXPLAIN (ANALYZE, BUFFERS) that the plan uses the range and that the aggregate does not spill to disk.
7Follow-up questions
Why can HAVING not be replaced by WHERE here?
Because the condition is about the total spent by a customer, which exists only after the rows have been grouped and summed. WHERE is evaluated earlier, on each order, so it cannot see the sum and SQL forbids aggregates there. Filtering single orders with WHERE total > 1000 would change the meaning and drop customers who reach 1000 through several smaller orders.
Could we use a subquery instead of HAVING?
Yes. We could compute the aggregates in a derived table or a CTE and filter the result with an outer WHERE spent > 1000. Many people find this clearer when several conditions refer to the same aggregates, because the alias can be used in the outer query. The plan is usually the same.
Why use a half-open range instead of EXTRACT(YEAR FROM created_at) = 2025?
Both give the same rows, but EXTRACT applies a function to the column for every row, so a plain index on created_at cannot be used for a range scan. The half-open range keeps the column bare and is also safe at the year boundary, with no gap and no overlap.
8Conclusion
In this answer, we built the report with a half-open date range in WHERE, GROUP BY customer_id, COUNT(*) for all orders and conditional aggregation for cancelled orders and non-cancelled spend, using either CASE expressions or PostgreSQL's FILTER clause. HAVING filters the groups after aggregation because WHERE runs before any sum exists, and SUM over no matching rows returns NULL, which COALESCE turns into 0 when we need a number.
Open with
I would filter 2025 in WHERE with a half-open range, created_at greater than or equal to 2025-01-01 and less than 2026-01-01, which keeps the column index friendly and avoids end-of-year edge cases.
Then, if they want more
Then GROUP BY customer_id. For the numbers I use conditional aggregation: COUNT star for all orders, COUNT star FILTER WHERE status is CANCELLED in PostgreSQL, or SUM of CASE WHEN CANCELLED THEN 1 ELSE 0 portably, and SUM of total FILTER WHERE status is not CANCELLED, or SUM of CASE WHEN not cancelled THEN total END.
To keep only customers who spent more than 1000, I put that condition in HAVING, because HAVING filters groups after aggregation, while WHERE runs on individual rows before any sum exists; WHERE total greater than 1000 would mean single orders over 1000 and drop customers who reach it with several small orders.
One edge case: SUM over zero matching rows is NULL, not 0, so a customer with only cancelled orders would get NULL spent; I wrap it in COALESCE when the value is displayed or mapped. For speed, an index on created_at, or a covering index with customer_id, status and total.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8.4
- 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.
- Official documentation
- PostgreSQL documentation, The SQL Language
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 "Using orders(customer_id, status, total, created_at), write one query that returns, per...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/6c79d88bb2/