Lessons › SQL › Chapter 4: Shaping data
SQL lesson
CASE WHEN
CASE WHEN gives each row a label by checking rules in order, like Low, Mid or High. SQL uses the first WHEN that's true. ELSE labels everything else, and END closes it.
Try this lesson free →Example
Label each row
SELECT order_id,
revenue,
CASE
WHEN revenue < 50 THEN 'Low'
WHEN revenue < 200 THEN 'Mid'
ELSE 'High'
END AS order_tier
FROM orders| order_id | revenue | order_tier |
|---|---|---|
| O2001 | 15.5 | Low |
| O2002 | 220.0 | High |
| O2003 | 85.75 | Mid |
| O2004 | 9.99 | Low |
| O2005 | 540.0 | High |
Step by step
- If the rule is true for a row, it gets that label.
SELECT order_id, revenue, CASE WHEN revenue < 50 THEN 'Low' WHEN revenue < 200 THEN 'Mid' ELSE 'High' END AS order_tier FROM orders - Add more WHENs. SQL uses the first one that's true.
SELECT order_id, revenue, CASE WHEN revenue < 50 THEN 'Low' WHEN revenue < 200 THEN 'Mid' ELSE 'High' END AS order_tier FROM orders - ELSE labels the rest. END closes it.
SELECT order_id, revenue, CASE WHEN revenue < 50 THEN 'Low' WHEN revenue < 200 THEN 'Mid' ELSE 'High' END AS order_tier FROM orders
Practice
1. Using orders, show revenue, and next to it a column called size: 'high' when revenue is more than 150, otherwise 'low'.
SELECT revenue, CASE WHEN revenue > 150 THEN 'high' ELSE 'low' END AS size FROM orders2. Using products, show price, and next to it a column called price_band: 'premium' when price is more than 100, otherwise 'budget'.
SELECT price, CASE WHEN price > 100 THEN 'premium' ELSE 'budget' END AS price_band FROM products3. Using orders, show category, and next to it a column called dept: 'tech' when category is 'Electronics', otherwise 'other'.
SELECT category, CASE WHEN category = 'Electronics' THEN 'tech' ELSE 'other' END AS dept FROM orders4. Using returns, show refund_amount, and next to it a column called refund_size: 'high' when refund_amount is more than 100, otherwise 'low'.
SELECT refund_amount, CASE WHEN refund_amount > 100 THEN 'high' ELSE 'low' END AS refund_size FROM returns5. Using employees, show salary, and next to it a column called band: 'senior' when salary is 70000 or more, 'mid' when it's 55000 or more, otherwise 'junior'.
SELECT salary, CASE WHEN salary >= 70000 THEN 'senior' WHEN salary >= 55000 THEN 'mid' ELSE 'junior' END AS band FROM employeesLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →