COALESCE
Return the first non-NULL value from a list — the portable way to supply a fallback.
Syntax
COALESCE(value1, value2, ..., valueN)| Parameter | Type | Notes |
|---|---|---|
| value1, value2, …* | any | Evaluated left to right. Returns the first one that isn't |
Example
SQL playground
Loading editor…
⌘/Ctrl + Enter
Fallback chains
Arguments don't have to be columns — mix columns, expressions, and a final literal default:
SQL playground
Loading editor…
⌘/Ctrl + Enter
COALESCE vs its dialect-specific cousins
| Function | Arguments | Portable? |
|---|---|---|
COALESCE(a, b, ...) | any number | yes — standard SQL |
IFNULL(a, b) | exactly 2 | MySQL, SQLite only |
ISNULL(a, b) | exactly 2 | SQL Server only (not the same as Postgres's ISNULL(), which doesn't exist there) |
NVL(a, b) | exactly 2 | Oracle only |
Prefer COALESCE unless you have a specific reason not to — it works
everywhere and isn't capped at two arguments.
Gotchas
- All arguments should share a compatible type. Mixing
COALESCE(amount, 'N/A')(number, then text) forces a cast and can throw or silently coerce depending on the engine — cast explicitly instead of relying on the mix. - It evaluates every argument up to the first non-NULL one, not lazily skip them entirely — an expensive subquery as an early argument still runs even when a later cheap one would've been the fallback anyway (some engines optimize this, don't rely on it).
COALESCE(x, 0)before dividing is the standard guard against aNULLpropagating through arithmetic — but decide if0is really the right default, versus excluding the row.
- NULL handling — three-valued logic and NULLIF, COALESCE's inverse.
- CASE — for fallback logic that depends on more than "is it NULL".
- AVG — a common place COALESCE guards against NULL-skewed averages.
Safety check before shipping
- confirm the fallback value makes sense for the column's actual type
- verify downstream logic treats the fallback the same as a real value would (or doesn't, if that matters)
- check whether a nullable column should stay nullable rather than be normalized away
Was this page helpful?