SQL CASE
If/else logic that returns a value.
Syntax
CASE WHEN condition THEN result … ELSE default END
Conditions are checked from the top and the first true one wins. Without ELSE the result is NULL. Works anywhere a value can go, including inside SUM.
Example
Query (on the shop database used in the SQL course)
SELECT name, price, CASE WHEN price >= 300 THEN 'premium' WHEN price >= 50 THEN 'mid-range' ELSE 'budget' END AS band FROM products ORDER BY price DESC LIMIT 6;
Result
| name | price | band |
|---|---|---|
| Standing desk | 549.0 | premium |
| Ergonomic chair | 399.0 | premium |
| 27-inch monitor | 329.0 | premium |
| Noise-cancelling headphones | 249.0 | mid-range |
| Mechanical keyboard | 119.0 | mid-range |
| Deep Learning (book) | 89.0 | mid-range |
6 rows
Related
Learn it step by step in the free lesson Functions: Text, Numbers, Dates & CASE, with exercises that check your queries.