CASE Expressions
Turn values into labels with CASE, and learn what happens with no ELSE, with NULL, and with the order of WHEN lines.
CASE is if and else for a value
CASE picks a result by testing conditions in order. Each WHEN holds a test and a THEN result. The first test that is true decides the answer, and the rest are skipped.
ELSE gives the result when no test is true. If you leave ELSE out and nothing matches, the result is NULL.
There is also a short form, CASE team WHEN 'Red' THEN 1 WHEN 'Blue' THEN 2 END, which compares one value with each WHEN value.
Labels without extra code
CASE lets a query return a ready-made label, such as a score band, instead of making every program repeat the same rules. It works anywhere an expression works.
Build score bands
SELECT name,
CASE WHEN points >= 30 THEN 'high'
WHEN points >= 20 THEN 'mid'
ELSE 'low'
END AS band
FROM players;Gus has 40 points, so the first test is true and he is high. Fay has 24: the first test is false, the second is true, so she is mid.
Chen has NULL points. Both tests are unknown, which is not true, so no WHEN matches and Chen falls through to ELSE. Chen is called low, which is probably not what you meant.
Compare four CASE versions
Switch between the versions and watch how the band changes for Gus, for Chen and for the players in between.
| nametext | pointsinteger | bandtext |
|---|---|---|
| Asha | 31 | high |
| Ben | 17 | low |
| Chen | NULL | low |
| Dara | 24 | mid |
| Eli | NULL | low |
| Fay | 24 | mid |
| Gus | 40 | high |
| Hana | 17 | low |
WHEN lines are checked top to bottom and the first true one wins. Chen and Eli have NULL points: both tests are UNKNOWN, so they fall to ELSE and are called low.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- CASE checks WHEN tests from the top and the first true one decides the result.
- With no ELSE and no true WHEN, CASE returns NULL.
- A test on a NULL value is unknown, so it does not match and the row falls through to ELSE.
- Put the most specific test first, and test IS NULL before the other tests when values can be missing.
Done with this concept?
Mark it complete to track your progress. No login needed.