CASE WHEN
Add conditional logic inside a query.
Questions this answers
- →How do I label rows based on their value?
- →How do I create custom categories from numeric ranges?
- →How do I count rows matching different conditions in one query?
- →How do I handle NULL differently in output?
How it works
CASE WHEN is SQL's if/else. It evaluates conditions in order and returns the first matching result. You can use it anywhere you'd use a column — in SELECT, ORDER BY, WHERE, or inside an aggregate.
Basic label
SELECT name,
CASE
WHEN monthly_listeners > 10000000 THEN 'Major'
WHEN monthly_listeners > 1000000 THEN 'Mid-tier'
ELSE 'Emerging'
END AS tier
FROM artists;Conditional count
SELECT COUNT(CASE WHEN genre = 'Pop' THEN 1 END) AS pop_count, COUNT(CASE WHEN genre = 'Rock' THEN 1 END) AS rock_count FROM artists;
💡 CASE inside COUNT is a common pattern for pivot-style queries.
In ORDER BY
SELECT name, genre
FROM artists
ORDER BY
CASE genre
WHEN 'Pop' THEN 1
WHEN 'Rock' THEN 2
ELSE 3
END;