SQL · Queries that survive scale
How does the CASE expression work?
Short answer
CASE returns a value based on the first matching condition. It works in SELECT, WHERE, ORDER BY, and aggregate expressions, and it is an expression rather than procedural control flow.
There are two forms. The searched form uses arbitrary boolean conditions. The simple form compares one expression against several values. The first matching branch wins, and ELSE supplies the default.
SELECT
id,
status,
CASE
WHEN status = 'paid' THEN 'complete'
WHEN status IN ('pending', 'authorized') THEN 'in_progress'
ELSE 'needs_attention'
END AS status_group
FROM orders;Conditional aggregation
SELECT
COUNT(*) AS total_orders,
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders,
SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded_orders
FROM orders;- If no branch matches and there is no ELSE, the result is NULL
- Conditions are evaluated in order, so put the most specific first
- CASE is not a control-flow statement and cannot contain statements
- Some engines support FILTER as a cleaner alternative for conditional aggregates
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens when no CASE branch matches and there is no ELSE?
- 2How do you compute conditional counts in one query?
- 3What is the difference between simple and searched CASE?
- 4Can CASE be used in ORDER BY?
Say it in the interview
CASE evaluates conditions in order and returns the value from the first match, with ELSE as the fallback. I use it for derived categories, conditional sorting, and conditional aggregation. Inside SUM or COUNT it lets one scan produce several business metrics. I always set an explicit ELSE when NULL would be ambiguous.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.