CASE Expression in SQL

Level 383 keystrokes

CASE expression adds conditional logic to SQL queries.

SQL code

-- Return each user's name and a computed status label
1SELECT
2 name,
-- CASE works like if/else and produces one value per row
3 CASE
-- If age is under 18, the result is 'Minor'
4 WHEN age < 18 THEN 'Minor'
-- Every other row gets 'Adult' (also when age is NULL)
5 ELSE 'Adult'
-- END closes the CASE, and AS status names the new column
6 END AS status
7FROM
8 users;

Output

+-------+--------+
| name  | status |
+-------+--------+
| Alice | Adult  |
| Bob   | Adult  |
| Tom   | Minor  |
+-------+--------+
3 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.

  • '× 4
  • ,× 1
  • ;× 1
  • <× 1

More SQL examples at level 3

← SQL typing practice