PostgreSQL NULL, COALESCE & NULLIF
NULL is SQL's marker for a missing or unknown value. It is not zero, not an empty string and not false. Three customers in the sample data have no email, and one author's birth year is unknown; both are stored as NULL. Handling NULL correctly is one of the most important SQL skills.
NULL is "unknown", and unknown spreads
Any arithmetic or comparison involving NULL gives NULL, because the answer is unknown too:
SELECT NULL + 1 AS plus,
NULL = NULL AS equals,
NULL <> 5 AS not_equals,
'a' || NULL AS concat,
NULL IS NULL AS is_null; plus | equals | not_equals | concat | is_null
------+--------+------------+--------+---------
| | | | t
(1 row)
SQL uses three-valued logic: true, false and unknown (NULL). WHERE keeps only true rows, which is why WHERE email = NULL finds nothing.
a |
b |
a AND b |
a OR b |
|---|---|---|---|
| true | NULL | NULL | true |
| false | NULL | false | NULL |
| NULL | NULL | NULL | NULL |
Testing for NULL
SELECT first_name, email FROM customers WHERE email IS NULL;
SELECT count(*) AS has_email FROM customers WHERE email IS NOT NULL; first_name | email
------------+-------
Chloé |
Gina |
Mia |
(3 rows)
has_email
-----------
12
(1 row)
IS DISTINCT FROM is a NULL-safe "not equal": it treats two NULLs as equal and NULL vs a value as different. That is useful when comparing two columns that may both be NULL:
SELECT a, b,
a <> b AS ordinary,
a IS DISTINCT FROM b AS null_safe
FROM (VALUES (1, 1), (1, 2), (1, NULL), (NULL, NULL)) AS t (a, b); a | b | ordinary | null_safe
---+---+----------+-----------
1 | 1 | f | f
1 | 2 | t | t
1 | | | t
| | | f
(4 rows)
COALESCE: the first non-NULL value
coalesce(a, b, c, …) returns its first argument that is not NULL. It is the standard way to supply a fallback:
SELECT first_name,
coalesce(email, 'no email on file') AS contact
FROM customers
WHERE id IN (1, 3, 7);
SELECT name, coalesce(birth_year::text, 'unknown') AS born
FROM authors
WHERE id >= 8; first_name | contact
------------+--------------------
Anna | anna.k@example.com
Chloé | no email on file
Gina | no email on file
(3 rows)
name | born
---------------+---------
Elena Petrova | 1968
Jonas Weber | unknown
Grace Liu | 1985
(3 rows)
All arguments of coalesce must have compatible types. That is why birth_year is cast to text before it can fall back to the word 'unknown'.
NULLIF: turn a value into NULL
nullif(a, b) returns NULL if a = b, otherwise a. Its classic use is avoiding division by zero: dividing by NULL gives NULL instead of an error.
SELECT title, price, stock, price / stock AS price_per_copy
FROM books WHERE id IN (1, 2);ERROR: division by zero
SELECT title, price, stock, round(price / nullif(stock, 0), 2) AS price_per_copy
FROM books WHERE id IN (1, 2); title | price | stock | price_per_copy
---------------+-------+-------+----------------
The Salt Road | 14.99 | 12 | 1.25
Harbor Lights | 12.50 | 0 |
(2 rows)
nullif is also handy for cleaning data, such as treating empty strings as missing: nullif(trim(phone), '').
NULL in aggregates, sorting and grouping
| Situation | What NULL does |
|---|---|
count(column), sum, avg, min, max |
ignored |
count(*) |
counted (it counts rows) |
ORDER BY |
sorted last in ascending order (unless NULLS FIRST) |
GROUP BY, DISTINCT |
all NULLs form one group |
UNIQUE constraint |
several NULLs are allowed (unless NULLS NOT DISTINCT) |
SELECT birth_year IS NULL AS unknown, count(*)
FROM authors
GROUP BY 1
ORDER BY 1;
CREATE TABLE t (code text UNIQUE);
INSERT INTO t VALUES (NULL), (NULL);
SELECT count(*) AS rows_with_null_code FROM t; unknown | count
---------+-------
f | 9
t | 1
(2 rows)
CREATE TABLE
INSERT 0 2
rows_with_null_code
---------------------
2
(1 row)
Tip: Decide deliberately whether a column may be NULL. If "missing" doesn't make sense (a price, a title), declare it
NOT NULLand you won't have to handle NULL in every query.
Test yourself
What is the result of NULL + 5?
- 5
- 0
- NULL
- An error
What does coalesce(NULL, NULL, 'x', 'y') return?
- NULL
- 'x'
- 'y'
- 'xy'
How can you avoid a division-by-zero error in total / count?
- total / coalesce(count, 0)
- total / nullif(count, 0)
- total / (count IS NULL)
- total // count