BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

order_idrevenueorder_tier
O200115.5Low
O2002220.0High
O200385.75Mid
O20049.99Low
O2005540.0High

Step by step

  1. 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
  2. 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
  3. 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

Try each one in your head first, then open the answer.

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 orders
2. 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 products
3. 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 orders
4. 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 returns
5. 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 employees

Learn 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 →
About 5–10 minutes · no sign-up needed