SQL CASE WHEN
CASE is SQL’s if-then-else. It checks conditions in order and returns the value for the first one that’s true. You can use it anywhere a value goes: in SELECT, ORDER BY, GROUP BY and inside aggregates.
Updated December 1, 2026
Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE fallback
END
Label rows into buckets
Conditions are checked top to bottom, so the second WHEN only sees drinks that cost $4 or more.
SELECT name, price,
CASE
WHEN price < 4 THEN 'budget'
WHEN price < 5 THEN 'standard'
ELSE 'premium'
END AS price_band
FROM drinks
ORDER BY price;
| name | price | price_band |
|---|---|---|
| Espresso | 3 | budget |
| Peppermint Tea | 3.25 | budget |
| Lemonade | 3.5 | budget |
| Hot Chocolate | 4 | standard |
| Cappuccino | 4.25 | standard |
| Latte | 4.5 | standard |
| Cold Brew | 4.75 | standard |
| Chai Latte | 4.75 | standard |
| Mocha | 5 | premium |
| Matcha Latte | 5.25 | premium |
Count conditionally
SUM(CASE WHEN ... THEN 1 ELSE 0 END) counts matching rows, so one query can produce several counts side by side.
SELECT COUNT(*) AS orders,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;
| orders | delivered | shipped | cancelled |
|---|---|---|---|
| 10 | 7 | 2 | 1 |
Custom sort order
Sort by business meaning instead of A–Z.
SELECT id, status
FROM orders
ORDER BY CASE status
WHEN 'shipped' THEN 1
WHEN 'delivered' THEN 2
ELSE 3
END, id;
| id | status |
|---|---|
| 4 | shipped |
| 8 | shipped |
| 1 | delivered |
| 2 | delivered |
| 3 | delivered |
| 6 | delivered |
Common mistakes
- Forgetting
END. EveryCASEneeds one. - Putting a broad condition first:
WHEN price < 5beforeWHEN price < 4means the second never wins. - Leaving out
ELSE, which returns NULL for anything unmatched.
Practice CASE WHEN interactively
Write real queries in your browser and get instant feedback in the lesson “CASE expressions” (Unit 7). New learners can start free from the first lesson.
Frequently asked questions
Is there an IF function in SQL?
CASE is the standard. MySQL also has IF(), SQL Server has IIF(), and SQLite has iif() in recent versions.
What is the short form of CASE?
CASE status WHEN 'shipped' THEN 1 ... END compares one value to a list of options, as in the sorting example above.