CASE WHEN
SQL · 15 questions
Short notes
Key idea
CASE WHEN is SQL's if/else. It returns a value per row, so you can label, bucket or conditionally count.
Syntax
CASE
WHEN amount >= 5000 THEN 'large'
WHEN amount >= 1000 THEN 'medium'
ELSE 'small'
END AS size
Conditions are tried top to bottom; the first true one wins.
Example
Count delivered and cancelled orders in one pass:
SELECT city,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY city;
This "pivot with CASE" is one of the most asked interview patterns.
Traps
- Order matters. Put the narrowest condition first, or
>= 1000will catch everything above 5000 too. - No
ELSEmeans NULL for rows that match nothing. - All branches should return the same type (don't mix text and numbers).
CASE x WHEN NULLnever matches; useCASE WHEN x IS NULL.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
A
CASEhas noELSE, and a row matches none of theWHENconditions. What does it return for that row? - Question 2medium
6 products cost under ₹700, and 9 cost under ₹1,000. What does this return?
SELECT COUNT(*) FROM products WHERE CASE WHEN price < 1000 THEN 'cheap' WHEN price < 700 THEN 'very cheap' ELSE 'other' END = 'very cheap'; - Question 3medium
What does this return?
SELECT SUM(CASE WHEN status IN ('cancelled', 'returned') THEN 1 ELSE 0 END) FROM orders; - Question 4medium
Which correctly labels customers with no city as 'Unknown'?
- Question 5hard
There are 80 orders and 12 are cancelled. What does this return?
SELECT COUNT(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) FROM orders;
CASE WHEN
CASE WHEN
CASE WHEN
CASE WHEN
CASE WHEN
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.