CASE: bucket rows into categories
Every column so far has come back exactly as stored. Sometimes what you want
isn't the raw value but a label based on it - "young" instead of 22,
"senior" instead of 61. CASE is SQL's inline if/else: it checks a series
of conditions in order and returns the first matching branch's value, right
inside a SELECT list.
CASE
WHEN age < 30 THEN 'young'
WHEN age < 50 THEN 'adult'
ELSE 'senior'
END
Each WHEN is checked top to bottom; the first one that's true wins, and
ELSE catches everything left over. Give the whole expression an alias with
AS and it behaves like any other column in your result.
There's a users table: id, name, age.
Your task: return each user's name, age, and a bracket column:
'young' if under 30, 'adult' if under 50, otherwise 'senior'.
You'll practice:
- Writing a multi-branch
CASE WHEN ... THEN ... ELSE ... END
- Aliasing a
CASE expression as a normal output column with AS