Multi-branch CASE in SQL

Level 4139 keystrokes

CASE can have multiple WHEN branches evaluated in order.

SQL code

-- Return each student's name, score and letter grade
1SELECT
2 name,
3 score,
-- WHEN branches are checked top to bottom; the first true one wins
4 CASE
-- 90 and above gets 'A'
5 WHEN score >= 90 THEN 'A'
-- Reached only if score < 90, so this means 80-89
6 WHEN score >= 80 THEN 'B'
-- 70-79 gets 'C'
7 WHEN score >= 70 THEN 'C'
-- Anything lower (or a NULL score) gets 'F'
8 ELSE 'F'
-- Name the result column grade
9 END AS grade
10FROM
11 students;

Output

+-------+-------+-------+
| name  | score | grade |
+-------+-------+-------+
| Alice |    95 | A     |
| Bob   |    82 | B     |
| Carol |    75 | C     |
| Dave  |    55 | F     |
+-------+-------+-------+
4 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • '× 8
  • =× 3
  • >× 3
  • ,× 2
  • ;× 1

More SQL examples at level 4

← SQL typing practice