lesson 14 Calculations & data quality · intermediate
Make decisions with CASE
Choose a result for each row using conditional logic.
the idea
CASE creates a value based on conditions. SQL checks WHEN branches in order and uses the first match. ELSE covers remaining rows.
tables in this lesson
The challenges use this data. Each column shows its type underneath; → marks a link to another table.
products4 columns · 6 rows
| idinteger · key | nametext | categorytext | pricereal |
|---|---|---|---|
| 1 | Notebook | Stationery | 12 |
| 2 | Desk lamp | Home | 45 |
| 3 | Keyboard | Tech | 80 |
| 4 | Pen set | Stationery | 8 |
| 5 | Headphones | Tech | 120 |
showing 5 of 6 rows
orders6 columns · 12 rows
| idinteger · key | customer_idinteger | product_idinteger | quantityinteger | statustext | ordered_attext |
|---|---|---|---|---|---|
| 101 | 1 | 1 | 2 | paid | 2025-01-01 |
| 102 | 2 | 3 | 1 | paid | 2025-01-02 |
| 103 | 1 | 2 | 1 | paid | 2025-01-05 |
| 104 | 3 | 5 | 2 | pending | 2025-01-08 |
| 105 | 4 | 4 | 5 | paid | 2025-02-01 |
showing 5 of 12 rows
example
The idea in one query. Press Run to see what it returns; running examples never affects your progress.
SELECT
name,
CASE
WHEN price >= 80 THEN 'Premium'
ELSE 'Standard'
END AS tier
FROM products;Watch for: Without ELSE, unmatched rows become NULL.
build it step by step
Each step changes one thing. Run them in order and watch the result change.
Read the prices you will classify. Each product has a price. CASE will label rows at or above 80 as Premium and the rest as Standard.
step-1.sqlSELECT name, price FROM products ORDER BY price;
Assign a tier with CASE. WHEN branches are checked in order. The first true branch wins; ELSE covers everything else.
step-2.sqlSELECT name, CASE WHEN price >= 80 THEN 'Premium' ELSE 'Standard' END AS tier FROM products;