×

sql · level 2 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

gives each row a value that depends on a test.

A shop wants a label beside each snack: sold out or in stock. CASE makes that choice for every row, like a fork in the road.

Write CASE, with a test, then THEN with the value to use if it passes. gives the value for every other row, and END closes the whole thing.

Name it with AS and it becomes a new column in the result. Leave out ELSE and rows that fail every test get NULL.

SELECT name, stock,
  CASE WHEN stock = 0 THEN 'sold out' ELSE 'in stock' END AS status
FROM snacks
ORDER BY stock;

CASE works anywhere a value can go, even inside an aggregate.