Learning navigation

Code with Animation

CASE Expressions

Turn values into labels with CASE, and learn what happens with no ELSE, with NULL, and with the order of WHEN lines.

SQL5 min readConcept 12 of 44

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.

SELECT name, points, CASE WHEN points >= 30 THEN 'high' WHEN points >= 20 THEN 'mid' ELSE 'low' END AS band
FROM players;
Result (8 rows)
nametextpointsintegerbandtext
Asha31high
Ben17low
ChenNULLlow
Dara24mid
EliNULLlow
Fay24mid
Gus40high
Hana17low

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.

  1. 1`CASE WHEN points >= 30 THEN 'high' END` is run for a player with 24 points. What is the result?
  2. 2Bands are `>= 30` high, `>= 20` mid, ELSE low. Chen's points are NULL. What band does Chen get?
  3. 3`CASE WHEN points >= 20 THEN 'mid' WHEN points >= 30 THEN 'high' ELSE 'low' END` is run for a player with 40 points. What is the result?

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.