SQL CASE WHEN
CASE WHEN adds if/then logic to a query: it checks conditions in order and returns the value of the first one that is true. It is how you label rows, build price bands and count several categories at once.
How do you label rows?
SELECT name, amount, CASE WHEN amount >= 1000 THEN 'large' WHEN amount >= 100 THEN 'medium' ELSE 'small' END AS sizeFROM orders;
The order matters. If the 100 check came first, every large order would be labelled medium.
How do you count categories in one query?
SELECT SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid, SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refundedFROM orders;
This "pivots" the categories into columns.
Can you group by a CASE?
Yes, repeat it in GROUP BY or group by its alias where the database allows it, for example to count orders per size band.
The ELSE trap
Without ELSE, rows that match no condition get NULL. That's fine for labels but changes the result inside SUM or AVG, so add ELSE 0 when you count.
Practise CASE
Updated November 2026.