Quick revision
The short answer
We use a searched CASE that tests the rules in priority order, new first, then active, then lapsed, with ELSE 'never ordered', and we GROUP BY that expression with COUNT(*). CASE returns the first branch that matches, so the order of the WHEN clauses is the priority. A NULL last_order_at makes the comparisons unknown, so those customers fall through to ELSE as intended.
What to remember
In this answer, we labelled customers with a searched CASE, where the first true branch wins, so the order new, active, lapsed is the rule priority and should be agreed with the report owner. We saw that comparisons with a NULL last_order_at are unknown and fall through to an explicit ELSE, that a missing ELSE would produce NULL labels, and that counting is a GROUP BY on the expression, most portably through a CTE.
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 use a searched CASE that tests the rules in priority order, new first, then active, then lapsed, with ELSE 'never ordered', and we GROUP BY that expression with COUNT(*). CASE returns the first branch that matches, so the order of the WHEN clauses is the priority. A NULL last_order_at makes the comparisons unknown, so those customers fall through to ELSE as intended.
Why this question is asked
Labelling rows into segments is one of the most common things reports do: customer status, risk band, ticket age. The SQL is short, but it hides two traps that interviewers like to probe: overlapping rules, where one customer matches several labels, and NULLs, which make comparisons neither true nor false. In this answer, we will recap the two forms of CASE, write the labelling query, look at why the order of branches is a business decision, follow what happens to NULL values, and count customers per label in a way that works in PostgreSQL and MySQL.
1A Quick Recap of CASE
CASE is an expression that returns a value chosen by conditions, much like if and else if in Java, but usable anywhere a value is allowed: in SELECT, WHERE, ORDER BY or GROUP BY. The simple form compares one value with several constants, such as CASE status WHEN 'P' THEN 'paid' WHEN 'C' THEN 'cancelled' END. The searched form, which we need here, has a full condition in each WHEN.
Two rules matter. CASE evaluates the WHEN conditions from top to bottom and returns the result of the first one that is true; later branches are never looked at. And if no branch is true and there is no ELSE, the result is NULL.
2Writing the Labelling Query
Our table is customers(id, created_at, last_order_at). The rules are: created in the last 30 days is 'new', ordered in the last 90 days is 'active', ordered before that is 'lapsed', and no order at all is 'never ordered'.
- Created in the last 30 days?YesnewNonext test
- Ordered in the last 90 days?YesactiveNonext test
- Has any order?last_order_at IS NOT NULLYeslapsedNoELSE
- never orderedalso where last_order_at is NULL
4 steps in order. Play them, or step through them one at a time.
The first true test wins, so the order of the tests is the priority of the rules.
Notice that the third branch does not repeat the 90 day condition. By the time CASE reaches it, every customer with a recent order has already been labelled 'active', so all that is left to check is whether an order exists at all. Writing it this way keeps the rules short and stops them from contradicting each other.
3Why the Order of the Branches Matters
Customer 1 in the example was created five days ago and ordered yesterday. That customer satisfies both the 'new' rule and the 'active' rule. Because 'new' comes first, they are labelled new. If we swapped the first two branches, the same data would give a different report: every new customer who already ordered would become active, and the 'new' segment would only contain new customers who have not ordered yet.
Neither choice is wrong in SQL, but they mean different things, so this is a question to settle with whoever owns the report. The useful habit is to make the priority visible: write the branches in the agreed order, and add a short comment above the CASE saying that the first match wins. Rules that overlap without an agreed order are how two teams end up with different counts for the same segment.
4What Happens to NULLs
For a customer who never ordered, last_order_at is NULL. Any comparison with NULL, such as NULL >= some_timestamp, gives unknown rather than true or false, and CASE treats unknown like false: it moves to the next branch.
So the NULL falls through to ELSE, which is exactly what we want. But this only works because we wrote an ELSE and because branch 3 uses IS NOT NULL, which is never unknown. If we had dropped the ELSE, these customers would get a NULL segment, and in the count they would show up as one row with an empty label that is easy to misread. Writing an explicit ELSE, even when we think all cases are covered, makes the report honest about leftovers.
5Counting Customers per Label
To count, we group by the same expression. The most portable way is to compute the label in a subquery or CTE and group by its column, so the CASE is written only once.
PostgreSQL and MySQL also let us write GROUP BY segment or GROUP BY 1 directly after a SELECT that defines the alias, which is shorter. The SQL standard does not allow an alias in GROUP BY, because logically GROUP BY runs before SELECT, so the CTE form is the one that works everywhere. In MySQL the interval syntax is written now() - INTERVAL 30 DAY.
One small point about time: now() returns the start time of the current transaction in PostgreSQL, so every row is compared with the same instant, which is what we want for a consistent report. If the report must use calendar days rather than rolling hours, we compare with current_date - 30 instead.
6Follow-up questions
Could a segment show zero customers and still appear in the result?
Not with this query. GROUP BY only produces groups that have at least one row. If the report must always show all four labels, we keep a small list of labels in a VALUES list or table and LEFT JOIN the counts to it, using COALESCE(count, 0).
Is it better to compute the label in Java instead?
For a count over all customers, no: the database can label and count millions of rows without sending them over the network. Computing in Java makes sense when the rules are complex and reused in business logic. Then we must make sure both places use the same rules, or better, keep one source of truth.
Can an index help this query?
Not much, because we count every customer, so the database reads the whole table anyway. An index on created_at helps only if we count a single segment, such as WHERE created_at >= now() - interval '30 days'.
7Conclusion
In this answer, we labelled customers with a searched CASE, where the first true branch wins, so the order new, active, lapsed is the rule priority and should be agreed with the report owner. We saw that comparisons with a NULL last_order_at are unknown and fall through to an explicit ELSE, that a missing ELSE would produce NULL labels, and that counting is a GROUP BY on the expression, most portably through a CTE.
Open with
I would write a searched CASE in the order of priority: when created_at is within the last 30 days, then 'new'; when last_order_at is within the last 90 days, then 'active'; when last_order_at is not null, then 'lapsed'; else 'never ordered'.
Then, if they want more
CASE returns the first branch that is true and ignores the rest, so the order of the WHEN clauses is really the business rule. A customer who signed up last week and ordered yesterday matches both new and active, and here they count as new.
If the business wants them active, I swap the branches, so I would confirm that with whoever owns the report. NULLs are handled by the structure: for a customer who never ordered, the comparison with last_order_at is unknown, which CASE treats as not matching, and the IS NOT NULL test is false, so they fall into ELSE.
I always write the ELSE, because without it unmatched rows get a NULL label. To count, I put the CASE in a CTE as a column called segment and then select segment and COUNT star with GROUP BY segment.
PostgreSQL and MySQL also accept GROUP BY with the alias directly, but the CTE is portable and keeps the rule in one place.
About this answer
- Last updated
- 12 November 2026
- 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 "Write a query over customers(id, created_at, last_order_at) that labels each customer as...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/f61d86d7a1/