skip to content

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.

query.sql
  1. 1SELECT name, price,
  2. 2 CASE WHEN price = 0 THEN 'free'
  3. 3 WHEN price < 25 THEN 'under 25'
  4. 4 WHEN price < 100 THEN 'under 100'
  5. 5 ELSE '100 and up'
  6. 6 END AS band
  7. 7FROM products
  8. 8WHERE id IN (4, 200, 1, 8, 5);
row =
price = 49.00
  1. 1. price = 0 → 'free'false
  2. 2. price < 25 → 'under 25'false
  3. 3. price < 100 → 'under 100'true: stop
  4. ELSE '100 and up'not reached
band =under 100

chef's knife falls past 2 tests and stops at test 3. the line below never gets looked at.

real output, postgres 18.6 (PGlite 0.5.12) · case-expressions
pick a product. it falls past the tests that are false, stops at the first one that's true, and never reaches the rest. the paper clips cost 0.00, which is also under 25 and under 100, but the first rung catches them.

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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 5
nametextpricenumericbandtext
paper clips, free sample0.00free
left-handed teapot19.99under 25
chef's knife49.00under 100
cat tree89.00under 100
studio headphones129.99100 and up
(5 rows)

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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 7
idint4statustextstagetext
880cancelleddone
1455refundeddone
6580delivereddone
7787delivereddone
8219delivereddone
9615delivereddone
9946placedin progress
(7 rows)

CASE status WHEN 'delivered' means CASE WHEN status = 'delivered'. which matters the moment you try to catch a NULL with it.

predict the output
sql
SELECT CASE category WHEN NULL THEN 'none' ELSE category END
FROM products
WHERE id = 7;   -- the wooden train, no category
sqldb=shop
SELECT 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;
output, from postgres 18.6
SELECT 1
simpletextsearchedtext
nullnone
(1 row)

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:

query.sql
  1. 1SELECT name,
  2. 2 coalesce(city, email, 'nothing on file') AS reach
  3. 3FROM customers
  4. 4WHERE id IN (42, 6, 11);
row =
city = '', email = null
  1. 1. city IS NOT NULL → citytrue: stop
  2. 2. email IS NOT NULL → emailnot reached
  3. 3. otherwise → 'nothing on file'not reached
reach =''

Ana Lima stops at the first test. the 2 lines below never get looked at.

real output, postgres 18.6 (PGlite 0.5.12) · case-expressions
three customers through 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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 3
idint4nametextcitytextcoalescedtextcleanedtext
6José Silvanullunknownunknown
11Ana Lima''''unknown
42Ada LovelaceLondonLondonLondon
(3 rows)

the second is dividing safely. dividing by zero is an error in postgres, and dividing by NULL is just NULL:

sqlempty db
SELECT 10 / 0;
output, from postgres 18.6
ERROR 22012: division by zero
sqlempty db
SELECT 10 / nullif(0, 0) AS ratio;
output, from postgres 18.6
SELECT 1
ratioint4
null
(1 row)

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:

ORDER BY =
query.sql
  1. 1SELECT status, count(*) AS orders
  2. 2FROM orders
  3. 3GROUP BY status
  4. 4ORDER BY status;
the result for status
statustextordersint8
cancelled317
delivered9352
paid62
placed51
refunded98
shipped120
(6 rows)

sorted by the text: alphabetical, which is nobody's idea of an order's life.

real output, postgres 18.6 (PGlite 0.5.12) · case-expressions
switch the sort key. by the text, statuses come out alphabetical. by a CASE that numbers them, they come out in the order an order lives them. the trailing 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:

sqldb=shop
SELECT CASE WHEN id > 0 THEN 1 ELSE 1 / 0 END
FROM products;
output, from postgres 18.6
ERROR 22012: division by zero

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.