What do COALESCE and NULLIF do, and how do they help handle NULL values?
Last updated
Both are NULL-handling functions: COALESCE returns the first non-NULL argument from a list (a substitute/default), while NULLIF turns a specific value into NULL by comparing two expressions.
COALESCE(a, b, c, ...):Returns the first argument that is not NULL, or NULL if all are NULL.
Great for defaults/fallbacks:
COALESCE(discount, 0)or picking the first available column.Standard SQL and portable; prefer it over vendor-specific
ISNULLorIFNULL.
NULLIF(a, b):Returns NULL if
a = b, otherwise returnsa.Common use: guard against divide-by-zero with
x / NULLIF(y, 0)(turns a 0 denominator into NULL instead of erroring).Also handy to treat sentinel values (like empty string) as NULL:
NULLIF(name, '').
They pair well together: Use
NULLIFto create NULLs, thenCOALESCEto collapse them into a safe default.
[lang:sql]
SELECT COALESCE(nickname, first_name, 'Guest') AS display_name,
revenue / NULLIF(orders, 0) AS avg_order_value
FROM users;
- https://learn.microsoft.com/en-us/sql/t-sql/language-elements/nullif-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql?view=sql-server-ver17
- https://www.postgresql.org/docs/current/functions-conditional.html
- https://medium.com/learning-data/advanced-sql-why-you-need-coalesce-and-nullif-for-null-data-with-business-examples-5b1b2b5c10fd
- https://reintech.io/blog/sql-coalesce-function-tutorial