CASE, COALESCE and NULLIF
if/else inside an expression, and the two shortcuts you'll type every week.
- address
- everything.basics.case_expressions
- part
- part 2, one table
- chapter
- chapter 7 of 12
- reading time
- 7 min
CASE is if/else inside an expression. postgres tries the WHENs top to bottom, the first one that's true wins, and if none is, you get the ELSE, or NULL when there's no ELSE.
two shortcuts cover most of what you'd write it for: COALESCE returns its first argument that isn't NULL, and NULLIF(a, b) returns NULL when a equals b.
the picture
you know how SQL has no if statement? you can't write "if the price is zero, say free" as a line of its own. what it has is better suited to a language where everything is a table: an expression that picks a value, row by row, and can go anywhere a value can go.
think of a coin sorter: a coin rolls down a ladder of slots, smallest first, and drops into the first one it fits. it never tries the slots below. CASE is that ladder, and each row is a coin.
- 1SELECT name, price,
- 2 CASE WHEN price = 0 THEN 'free'
- 3 WHEN price < 25 THEN 'under 25'
- 4 WHEN price < 100 THEN 'under 100'
- 5 ELSE '100 and up'
- 6 END AS band
- 7FROM products
- 8WHERE id IN (4, 200, 1, 8, 5);
- 1. price = 0 → 'free'false
- 2. price < 25 → 'under 25'false
- 3. price < 100 → 'under 100'true: stop
- ELSE '100 and up'not reached
chef's knife falls past 2 tests and stops at test 3. the line below never gets looked at.
order is the whole trick. the tests overlap (anything under 25 is also under 100), and that's fine, because a row only gets to the third test after failing the second. swap the rungs and the teapot would land in "under 100". so put the narrow tests first.
the same query for real, every row of it:
SELECT name, price,
CASE WHEN price = 0 THEN 'free'
WHEN price < 25 THEN 'under 25'
WHEN price < 100 THEN 'under 100'
ELSE '100 and up'
END AS band
FROM products
WHERE id IN (4, 200, 1, 8, 5)
ORDER BY price;| nametext | pricenumeric | bandtext |
|---|---|---|
| paper clips, free sample | 0.00 | free |
| left-handed teapot | 19.99 | under 25 |
| chef's knife | 49.00 | under 100 |
| cat tree | 89.00 | under 100 |
| studio headphones | 129.99 | 100 and up |
two spellings
that's the searched CASE: every WHEN is a full condition. when every test compares the same thing with =, the simple CASE says it once:
SELECT id, status,
CASE status
WHEN 'delivered' THEN 'done'
WHEN 'cancelled' THEN 'done'
WHEN 'refunded' THEN 'done'
ELSE 'in progress'
END AS stage
FROM orders
WHERE customer_id = 42
ORDER BY id;| idint4 | statustext | stagetext |
|---|---|---|
| 880 | cancelled | done |
| 1455 | refunded | done |
| 6580 | delivered | done |
| 7787 | delivered | done |
| 8219 | delivered | done |
| 9615 | delivered | done |
| 9946 | placed | in progress |
CASE status WHEN 'delivered' means CASE WHEN status = 'delivered'. which matters the moment you try to catch a NULL with it.
SELECT CASE category WHEN NULL THEN 'none' ELSE category END
FROM products
WHERE id = 7; -- the wooden train, no categorySELECT CASE category WHEN NULL THEN 'none' ELSE category END AS simple,
CASE WHEN category IS NULL THEN 'none' ELSE category END AS searched
FROM products
WHERE id = 7;| simpletext | searchedtext |
|---|---|
| null | none |
COALESCE
"use this, or if it's missing, that" comes up so often it has its own function. coalesce(a, b, c) returns the first argument that isn't NULL. it's a CASE ladder where every rung asks IS NOT NULL:
- 1SELECT name,
- 2 coalesce(city, email, 'nothing on file') AS reach
- 3FROM customers
- 4WHERE id IN (42, 6, 11);
- 1. city IS NOT NULL → citytrue: stop
- 2. email IS NOT NULL → emailnot reached
- 3. otherwise → 'nothing on file'not reached
Ana Lima stops at the first test. the 2 lines below never get looked at.
coalesce(city, email, 'nothing on file'). José has no city, so he falls through to his email. Ana's city is an empty string, which is not NULL, so coalesce stops there and hands back ''.that's the classic trap. coalesce rescues you from NULL, and only from NULL. an empty string, a zero, the string 'Null' (customer 10 says hi) are all values, and coalesce returns them without a second look. it's also standard SQL, unlike the ifnull and nvl you might know from mysql or oracle.
like a CASE, it stops at the first hit: the arguments after it are never evaluated. so coalesce(cheap_column, expensive_function()) only pays for the function when it has to.
NULLIF
nullif(a, b) is the opposite move: it returns NULL when a = b, and a otherwise. it turns a value you don't want into NULL. two uses cover nearly all of it.
the first is cleaning up Ana. treat an empty city as no city, and then coalesce can do its job:
SELECT id, name,
city,
coalesce(city, 'unknown') AS coalesced,
coalesce(nullif(city, ''), 'unknown') AS cleaned
FROM customers
WHERE id IN (6, 11, 42)
ORDER BY id;| idint4 | nametext | citytext | coalescedtext | cleanedtext |
|---|---|---|---|---|
| 6 | José Silva | null | unknown | unknown |
| 11 | Ana Lima | '' | '' | unknown |
| 42 | Ada Lovelace | London | London | London |
the second is dividing safely. dividing by zero is an error in postgres, and dividing by NULL is just NULL:
SELECT 10 / 0;SELECT 10 / nullif(0, 0) AS ratio;| ratioint4 |
|---|
| null |
so sum(x) / nullif(count(*), 0) returns NULL for an empty group instead of stopping the whole query.
CASE anywhere
CASE is an expression, so it goes wherever a value goes: SELECT, WHERE, ORDER BY, GROUP BY, inside an aggregate. in ORDER BY it lets you invent an order the data doesn't have. order statuses sort alphabetically by default, which puts cancelled first and shipped last:
- 1SELECT status, count(*) AS orders
- 2FROM orders
- 3GROUP BY status
- 4ORDER BY status;
| statustext | ordersint8 |
|---|---|
| cancelled | 317 |
| delivered | 9352 |
| paid | 62 |
| placed | 51 |
| refunded | 98 |
| shipped | 120 |
sorted by the text: alphabetical, which is nobody's idea of an order's life.
status breaks the tie between cancelled and refunded, which share the 5.inside an aggregate, CASE counts things conditionally: sum(CASE WHEN discontinued THEN 1 ELSE 0 END) counts discontinued products. postgres has a tidier spelling for that, count(*) FILTER (WHERE discontinued), and FILTER and pivoting is all about it.
one level deeperwhen the ladder doesn't protect you
the manual promises that a CASE evaluates only the branch it needs, and that's what makes CASE WHEN x <> 0 THEN 1 / x END safe. two exceptions are worth knowing.
constant expressions get simplified when the query is planned, before any row is read. 1 / 0 is a constant, so planning it fails even if no row would ever reach that branch:
SELECT CASE WHEN id > 0 THEN 1 ELSE 1 / 0 END
FROM products;every product has an id over 0, and it still fails. and aggregates inside a CASE are computed for the whole group up front, before the CASE looks at anything, so a CASE can't stop an aggregate from dividing by zero. keep dangerous arithmetic out of constants, and put the guard (a nullif) inside the aggregate, not around it.
keylines
- CASE tries its WHENs in order and stops at the first true one. no match and no ELSE gives NULL.
- put the narrow tests first: later rungs only see rows that failed the earlier ones.
- CASE x WHEN NULL never fires. use CASE WHEN x IS NULL.
- COALESCE returns the first non-NULL argument. '' and 0 aren't NULL.
- NULLIF(a, b) makes a value NULL: empty strings, and divisors that might be zero.