runtime
14 / 88

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 · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-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.

example.sql
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.

  1. 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.sql
    SELECT name, price
    FROM products
    ORDER BY price;
  2. Assign a tier with CASE. WHEN branches are checked in order. The first true branch wins; ELSE covers everything else.

    step-2.sql
    SELECT
      name,
      CASE
        WHEN price >= 80 THEN 'Premium'
        ELSE 'Standard'
      END AS tier
    FROM products;

challenge 1

Show name and tier: Premium if price >= 80, otherwise Standard.

Return nametierany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.