ConditionalSQL standard

COALESCE

Returns the first value in the list that isn't NULL.

Syntax

COALESCE(<value1>, <value2>, …)

Checks the arguments from left to right and returns the first one that isn't NULL. If they're all NULL, the result is NULL too. Most often it's used to substitute a default value, for example: “no phone number — show a dash”.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

The first value that isn't NULL
SELECT COALESCE(NULL, NULL, 42) AS result;
result
42
A dash instead of an empty phone number
SELECT name, COALESCE(phone, '—') AS phone
FROM employees;
namephone
Emma+44 7700 900123
Liam—
Olivia+44 7700 900456
Noah+44 7700 900789
Sophia—
NULL “swallows” arithmetic
SELECT name,
salary + bonus AS without_coalesce,
salary + COALESCE(bonus, 0) AS total
FROM employees;
namewithout_coalescetotal
Emma15001500
LiamNULL1000
Olivia15001500
NoahNULL950
Sophia14001400

Any operation with NULL gives NULL: Liam and Noah have no bonus, so without COALESCE their total would vanish completely.

Watch out

The arguments must have compatible types. COALESCE(bonus, 'n/a') on a numeric bonus throws an error: PostgreSQL tries to turn 'n/a' into a number. Cast to text: COALESCE(bonus::text, 'n/a').

An empty string '' isn't NULL, so COALESCE won't replace it. For that, combine it with NULLIF: COALESCE(NULLIF(phone, ''), '—').

Related functions

Learn more in the course