CASE WHEN
Part of the Beyond the Basics section of Coddy's SQL journey — lesson 1 of 27.
A CASE expression is an if/else if/else for SQL. It lives inside SELECT (or ORDER BY, or WHERE) and produces a value per row.
SELECT name,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 75 THEN 'B'
WHEN score >= 60 THEN 'C'
ELSE 'F'
END AS grade
FROM studentsEach WHEN is checked top-down; the first match wins. The ELSE is optional. Without it, unmatched rows get NULL.
Always end with END and give the column a name with AS.
Challenge
EasyAvailable tables and columns:
<strong>employees</strong>:<strong>id</strong>,<strong>name</strong>,<strong>department</strong>,<strong>salary</strong>
For each employee return their name, department, and a tier column built like this:
'partner'whensalary >= 150000(any department)'senior'whendepartment = 'eng'andsalary >= 100000'mid'whensalary >= 60000'entry'otherwise
Order by salary descending. Note that the order of the WHEN branches matters: the first match wins.
Cheat sheet
CASE acts as if/else inside SELECT, producing a value per row:
SELECT name,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 75 THEN 'B'
ELSE 'F'
END AS grade
FROM students- Conditions are checked top-down; first match wins
ELSEis optional — without it, unmatched rows returnNULL- Always close with
END; useASto name the column
Try it yourself
SELECT name, department,
-- tier with multiple WHEN branches that mix salary and department
FROM employees
This lesson includes a short quiz. Start the lesson to answer it and track your progress.