Use IS [NOT] NULL, COALESCE, NULLIF and related functions to detect, replace, or compare NULL values.
PostgreSQL treats NULL as "unknown." Learn how to test, replace, and compare NULLs using built-in operators and functions.
NULL represents an unknown or missing value. It is not zero or an empty string and never equals anything—not even another NULL.
Use the IS NULL and IS NOT NULL predicates. Avoid using = NULL
because it always returns false.
SELECT id FROM orders WHERE shipped_at IS NULL;
COALESCE returns the first non-NULL argument. It is the most common way to provide defaults.
SELECT COALESCE(discount, 0) AS discount
FROM invoices;
Use NULLIF to convert identical values to NULL and IS DISTINCT FROM for safe comparisons.
-- Avoid division by zero
SELECT amount / NULLIF(quantity, 0) AS unit_price
FROM sales;
-- Safe equality test
SELECT *
FROM a FULL JOIN b ON a.key IS NOT DISTINCT FROM b.key;
COUNT, SUM, AVG, MIN, and MAX automatically ignore NULLs. Use COUNT(*) to include NULL rows or FILTER for precise control.
SELECT COUNT(*) AS total_rows,
COUNT(price) AS priced_rows,
AVG(price) FILTER (WHERE price IS NOT NULL) AS avg_price
FROM products;
Use it in JOINs or comparisons where NULL = NULL should evaluate to true, unlike standard equality.
1. Store NULL only when data is truly unknown.
2. Use COALESCE in SELECT, not in WHERE, to avoid hiding NULL logic.
3. Prefer IS DISTINCT FROM over COALESCE for comparisons to retain type safety.
1. Testing with = NULL
—always false.
2. Mixing data types in COALESCE, which forces unwanted casts.
Yes. COUNT(*) counts every row, regardless of NULLs. To skip NULLs, use COUNT(column_name).
Yes. Define the column with NOT NULL and a DEFAULT clause: last_login TIMESTAMP NOT NULL DEFAULT now()
.
No, but COALESCE provides the same functionality and supports more than two arguments.