NULL in SQL: Three-Valued Logic, IS NULL, COALESCE and NULLIF
Everything about NULL that causes real bugs: what it means, why = NULL never matches, three-valued logic with AND, OR and NOT, IS NULL, IS DISTINCT FROM, COALESCE and NULLIF, and how NULL behaves in arithmetic, constraints, aggregates, grouping, sorting and unique keys.
kvi5hnuCode Sprout team member13 min readOn this page
NULL is SQL's marker for a missing value. It shows up everywhere: a customer with no phone number, a product whose weight hasn't been measured yet, an order that hasn't shipped and so has no ship date. NULL is simple to describe and surprisingly easy to get wrong, because it doesn't behave like a value. This article covers all the rules in one place. You'll meet them again in nearly every later article.
What NULL means
NULL means "there's no value here". In practice, that covers several situations:
- unknown: the value exists, but we don't know it (the lantern's weight);
- missing: the value was never collected (a customer who didn't give a phone number);
- not applicable: there's no value to have (the ship date of a cancelled order).
SQL treats all of them the same way. And NULL is not a value of any kind:
- It isn't zero. A product with NULL stock is different from one with zero stock.
- It isn't an empty string.
''is a real string that happens to have no characters (except in Oracle, which treats''as NULL). - It isn't equal to another NULL. Two unknown values aren't known to be the same.
The examples use the Part 2 products table, where the Basecamp lantern has no brand and no weight. They start with a psql command, \pset null '(null)', which makes NULLs visible in the output. By default psql shows a NULL as a blank cell, which looks exactly like an empty string.
Testing for NULL: IS NULL
Because NULL isn't equal to anything, you can't find it with =:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- psql command: show NULL as (null) instead of a blank cell
-- = NULL is never true, so this finds nothing
SELECT name, brand FROM products WHERE brand = NULL;
-- IS NULL and IS NOT NULL are the only reliable tests
SELECT name, brand, weight_g FROM products WHERE brand IS NULL OR weight_g IS NULL;
SELECT count(*) AS with_brand FROM products WHERE brand IS NOT NULL;
-- NULL is not zero and not an empty string
SELECT NULL = 0 AS null_eq_zero, NULL = '' AS null_eq_empty, NULL = NULL AS null_eq_null,
NULL IS NULL AS null_is_null, '' IS NULL AS empty_is_null;
name | brand
------+-------
(0 rows)
name | brand | weight_g
------------------+--------+----------
Basecamp lantern | (null) | (null)
(1 row)
with_brand
------------
6
(1 row)
null_eq_zero | null_eq_empty | null_eq_null | null_is_null | empty_is_null
--------------+---------------+--------------+--------------+---------------
(null) | (null) | (null) | t | f
(1 row)
brand = NULL returned no rows, without any error. Any comparison with NULL, whether =, <>, < or >, gives NULL, which here means unknown. Even NULL = NULL is unknown. The only reliable tests are the predicates IS NULL and IS NOT NULL, which are always true or false, never unknown.
Writing = NULL instead of IS NULL is one of the most common SQL mistakes, and it's silent. Some tools warn about it, but the database itself accepts it.
Three-valued logic
Since a comparison can be true, false or unknown, SQL uses three-valued logic. The operators AND, OR and NOT extend in the natural way. Think of unknown as "could be either":
ANDis false if either side is false, true only if both are true, and unknown otherwise. False wins.ORis true if either side is true, false only if both are false, and unknown otherwise. True wins.NOT unknownis unknown.
The query below builds the complete truth table, using PostgreSQL's BOOLEAN type and showing NULL as unknown:
\pset null 'unknown'
-- Every combination of true, false and unknown (NULL)
SELECT a.v AS a, b.v AS b,
a.v AND b.v AS "a AND b",
a.v OR b.v AS "a OR b",
NOT a.v AS "NOT a"
FROM (VALUES (true), (false), (NULL::boolean)) AS a(v)
CROSS JOIN (VALUES (true), (false), (NULL::boolean)) AS b(v);
a | b | a AND b | a OR b | NOT a
---------+---------+---------+---------+---------
t | t | t | t | f
t | f | f | t | f
t | unknown | unknown | t | f
f | t | f | t | t
f | f | f | f | t
f | unknown | f | unknown | t
unknown | t | unknown | t | unknown
unknown | f | f | unknown | unknown
unknown | unknown | unknown | unknown | unknown
(9 rows)

These tables explain every NULL surprise in WHERE clauses:
WHERE(andONandHAVING) keeps a row only when the condition is true. Unknown counts as "not true", so the row is dropped.- That's why
brand <> 'Kestrel'dropped the lantern in article 6:NULL <> 'Kestrel'is unknown. NOTdoesn't rescue it:NOT (brand = 'Kestrel')is also unknown for the lantern. A row can fail both a condition and its negation. SoWHERE x = 1andWHERE NOT (x = 1)don't always add up to the whole table.x NOT IN (1, NULL)isx <> 1 AND x <> NULL, which is... AND unknown. That can never be true (article 7).- In contrast,
brand = 'Lumen' OR stock > 10is true for the lantern, even though its brand is NULL, becausestock > 10is true and true wins in anOR.
Replacing NULL: COALESCE
COALESCE(a, b, c, ...) returns its first argument that isn't NULL, or NULL if all of them are. It's the standard way to substitute a default value.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- COALESCE returns its first non-NULL argument
SELECT name,
brand,
COALESCE(brand, 'unbranded') AS brand_label,
COALESCE(weight_g, 0) AS weight_or_zero,
COALESCE(CAST(weight_g AS VARCHAR(10)), 'unknown') AS weight_text
FROM products
WHERE product_id IN (3, 4)
ORDER BY product_id;
-- NULLIF(a, b) returns NULL when a = b, otherwise a
SELECT NULLIF(0, 0) AS zero_becomes_null, NULLIF(5, 0) AS five_stays, NULLIF('', '') AS empty_becomes_null;
-- NULL-safe comparison: NULL is treated as an ordinary value
SELECT name, brand,
brand <> 'Kestrel' AS ordinary_not_equal,
brand IS DISTINCT FROM 'Kestrel' AS is_distinct_from
FROM products
WHERE category IN ('lighting', 'packs')
ORDER BY product_id;
name | brand | brand_label | weight_or_zero | weight_text
------------------+--------+-------------+----------------+-------------
Glow head torch | Lumen | Lumen | 90 | 90
Basecamp lantern | (null) | unbranded | 0 | unknown
(2 rows)
zero_becomes_null | five_stays | empty_becomes_null
-------------------+------------+--------------------
(null) | 5 | (null)
(1 row)
name | brand | ordinary_not_equal | is_distinct_from
-------------------+---------+--------------------+------------------
Glow head torch | Lumen | t | t
Basecamp lantern | (null) | (null) | t
Trail 30 backpack | Kestrel | f | f
Day 18 backpack | Kestrel | f | f
(4 rows)
COALESCE(brand, 'unbranded')labels the lantern instead of leaving a hole in a report.COALESCE(weight_g, 0)substitutes a number. Only do this when zero really is the right answer for your calculation. An unknown weight isn't actually zero, so summing weights this way would understate the total without any sign that data is missing.- All of
COALESCE's arguments must have compatible types. To show the wordunknownin a numeric column, the number must first be converted to text, which is whatCAST(weight_g AS VARCHAR(10))does.COALESCE(weight_g, 'unknown')would fail, because'unknown'isn't a valid integer.
Every product also has its own two-argument version: NVL in Oracle, IFNULL in MySQL and SQLite, and ISNULL in SQL Server. Oracle also has NVL2(x, a, b), which returns a when x isn't NULL and b when it is, the same as CASE WHEN x IS NOT NULL THEN a ELSE b END. They differ in details. For example, SQL Server's ISNULL uses the first argument's type for the result, so ISNULL(short_column, 'a much longer default') can truncate the default. Prefer COALESCE, which is standard, works everywhere and accepts any number of arguments.
Creating NULL: NULLIF
NULLIF(a, b) is the opposite: it returns NULL if a = b, and a otherwise. Two common uses:
- Safe division:
total / NULLIF(count, 0)gives NULL instead of a division-by-zero error (article 5). - Cleaning "fake" missing values:
NULLIF(phone, '')turns empty strings into real NULLs, andNULLIF(score, -1)turns a "no data" code into NULL. After that, the NULL rules (such as aggregates ignoring NULLs) work for you.
Comparing values that might be NULL: IS DISTINCT FROM
Sometimes you want a comparison that treats NULL as an ordinary value, so that two NULLs count as equal and a NULL differs from any real value. The standard predicate for that is IS DISTINCT FROM, and its negation, IS NOT DISTINCT FROM:
| a | b | a = b | a IS NOT DISTINCT FROM b |
|---|---|---|---|
| 1 | 1 | true | true |
| 1 | 2 | false | false |
| 1 | NULL | unknown | false |
| NULL | NULL | unknown | true |
In the example, brand IS DISTINCT FROM 'Kestrel' is true for the lantern, while brand <> 'Kestrel' is unknown. This is exactly what you need when comparing an old and a new version of a row ("did this column change?"), or when matching rows from two tables where both may be NULL.
PostgreSQL, SQLite and SQL Server 2022 and later support IS [NOT] DISTINCT FROM. MySQL has an operator for it, <=> (NULL-safe equals), so a <=> b means a IS NOT DISTINCT FROM b. Oracle has neither, but DECODE(a, b, 1, 0) = 1 treats two NULLs as equal, and so does the longer (a = b OR (a IS NULL AND b IS NULL)).
NULL in expressions and functions
- Arithmetic: any operation with a NULL operand gives NULL.
price * NULLis NULL. - Concatenation:
'a' || NULLis NULL in standard SQL and PostgreSQL. Oracle treats the NULL as an empty string, andCONCATskips NULLs in PostgreSQL, SQL Server, Oracle and SQLite, but returns NULL in MySQL (article 5). - Most functions return NULL when an argument is NULL, such as
UPPER(NULL),ROUND(NULL)andLENGTH(NULL). Functions designed for NULLs, such asCOALESCE, are the exception. CASEcan test for NULL explicitly withWHEN x IS NULL THEN .... But a simpleCASE x WHEN NULL THEN ...never matches, because it compares with=(article 11).
NULL in constraints, aggregates, grouping and sorting
NULL also has rules outside WHERE. This example shows the important ones:
\pset null '(null)'
CREATE TABLE members (
member_id INTEGER PRIMARY KEY,
email VARCHAR(60) UNIQUE,
city VARCHAR(30),
points INTEGER CHECK (points >= 0)
);
INSERT INTO members VALUES
(1, 'asha@example.com', 'Pune', 120),
(2, NULL, 'Leeds', NULL),
(3, NULL, NULL, 40),
(4, 'ben@example.com', 'Leeds', NULL);
-- UNIQUE allows several NULLs: two members have no email
SELECT member_id, email FROM members ORDER BY member_id;
-- A CHECK constraint rejects only FALSE, so NULL points passed it
INSERT INTO members VALUES (5, 'neg@example.com', 'York', -10);
-- Aggregates skip NULLs; COUNT(*) counts rows
SELECT COUNT(*) AS members, COUNT(points) AS with_points, SUM(points) AS total, AVG(points) AS average
FROM members;
-- DISTINCT and GROUP BY treat all NULLs as one group
SELECT city, COUNT(*) AS n FROM members GROUP BY city ORDER BY city;
-- Sorting: PostgreSQL puts NULLs last in ascending order, unless told otherwise
SELECT member_id, city FROM members ORDER BY city NULLS FIRST, member_id;
member_id | email
-----------+------------------
1 | asha@example.com
2 | (null)
3 | (null)
4 | ben@example.com
(4 rows)
psql:/workspace/solution.sql:18: ERROR: new row for relation "members" violates check constraint "members_points_check"
DETAIL: Failing row contains (5, neg@example.com, York, -10).
members | with_points | total | average
---------+-------------+-------+---------------------
4 | 2 | 160 | 80.0000000000000000
(1 row)
city | n
--------+---
Leeds | 2
Pune | 1
(null) | 1
(3 rows)
member_id | city
-----------+--------
3 | (null)
2 | Leeds
4 | Leeds
1 | Pune
(4 rows)
- UNIQUE allows several NULLs. Members 2 and 3 both have no email. In standard SQL, two NULLs aren't equal, so they don't violate uniqueness. PostgreSQL, Oracle, MySQL and SQLite follow this rule. SQL Server is the exception: a
UNIQUEconstraint allows only one NULL. To allow many there, use a filtered unique index instead:CREATE UNIQUE INDEX ux_members_email ON members (email) WHERE email IS NOT NULL;. When you want at most one NULL, PostgreSQL 15 and later support the SQL optionUNIQUE NULLS NOT DISTINCT. - CHECK constraints reject only false. The constraint
points >= 0rejected -10, but it accepted NULL for members 2 and 4, becauseNULL >= 0is unknown, and a check only fails when the condition is false. If NULL shouldn't be allowed, addNOT NULLas well. - Aggregates ignore NULLs.
COUNT(points)counted only the two members with points,SUMadded 120 + 40, andAVGdivided by 2, not by 4.COUNT(*)counts rows, whatever they contain. Part 4 covers aggregates in detail. If NULL should count as zero in an average, writeAVG(COALESCE(points, 0))and accept that you're changing the question. GROUP BYandDISTINCTput all NULLs in one group. Here, unlike in comparisons, NULLs are treated as equal to each other. Member 3's NULL city formed its own group.- Sorting puts NULLs together, at one end. PostgreSQL and Oracle sort NULLs last in ascending order (and first in descending order). MySQL, SQL Server and SQLite sort them first in ascending order. The standard lets you choose with
NULLS FIRSTorNULLS LAST, which PostgreSQL, Oracle and SQLite support. Article 9 shows how to get the same effect in MySQL and SQL Server.
Designing with NULL
Because NULL complicates every query that touches a column, decide deliberately whether each column should allow it:
- Declare columns
NOT NULLunless "no value" is a real, meaningful state. Most columns in a well-designed table areNOT NULL. - Don't use sentinel values, such as
-1,'N/A'or1900-01-01, to mean "missing". They look like real data, so aggregates and comparisons treat them as real values. Use NULL, or a separate status column. - Don't let both NULL and
''mean "missing" in the same column. Pick one, and enforce it with aCHECKconstraint such asCHECK (phone <> ''). - When a column's meaning has several kinds of "missing", such as "not asked", "refused" and "not applicable", NULL can't tell them apart. Model them explicitly, for example with a status column.
What's current
UNIQUE NULLS [NOT] DISTINCTwas standardized in SQL and has been in PostgreSQL since version 15. It lets a unique constraint treat NULLs as equal.IS [NOT] DISTINCT FROMreached SQL Server in 2022, so it's now available in PostgreSQL, SQL Server and SQLite. MySQL still uses<=>.- Oracle 23ai and later support the SQL
BOOLEANtype, so you can now store and select the results of conditions, including unknown (NULL), in Oracle too. Oracle still treats''as NULL.
Common questions
Why doesn't WHERE column = NULL give an error?
Because it's valid SQL. It compares the column with NULL, gets unknown for every row, and so returns nothing. Use IS NULL.
Is NULL equal to NULL?
In comparisons, no: NULL = NULL is unknown. In GROUP BY, DISTINCT, UNION and PARTITION BY, NULLs are treated as one group. And IS NOT DISTINCT FROM treats them as equal on purpose.
Should I use NULL or an empty string for a missing value?
NULL, in general. It's the standard marker, aggregates and IS NULL understand it, and it's the only option that works in Oracle, where '' becomes NULL anyway. Whatever you choose, use one representation consistently.
Why does COUNT(column) give a smaller number than COUNT(*)?
COUNT(column) counts the rows where the column isn't NULL. COUNT(*) counts all rows.
Does an index store NULLs?
In PostgreSQL, SQL Server, MySQL and SQLite, yes, so WHERE col IS NULL can use an index. In Oracle, a B-tree index on a single column doesn't store rows where that column is NULL, so IS NULL can't use it. A common workaround is a composite index that includes a constant or a NOT NULL column.
What's the difference between COALESCE and NULLIF?
They're opposites. COALESCE(x, d) replaces a NULL with a value. NULLIF(x, v) replaces a value with NULL.
Can a primary key be NULL?
No. A primary key is implicitly NOT NULL. A UNIQUE column can be NULL unless you also declare it NOT NULL.
Summary
- NULL marks a missing, unknown or not-applicable value. It isn't zero, an empty string or equal to anything, including another NULL.
- Comparisons with NULL give unknown. Use
IS NULLandIS NOT NULLto test for it. - SQL uses three-valued logic.
AND: false wins.OR: true wins.NOT unknownis unknown. WHERE,ONandHAVINGkeep only rows where the condition is true.CHECKconstraints reject only rows where it's false.COALESCEreturns the first non-NULL argument.NULLIF(a, b)returns NULL whena = b.IS DISTINCT FROM(MySQL:<=>) compares values treating NULL as an ordinary value.- NULL propagates through arithmetic,
||and most functions. - Aggregates ignore NULLs except
COUNT(*).GROUP BYandDISTINCTgroup NULLs together.UNIQUEallows several NULLs, except in SQL Server. - NULLs sort last in ascending order in PostgreSQL and Oracle, and first in MySQL, SQL Server and SQLite.
Practice questions
A customers table has 100 rows. WHERE country = 'IN' returns 30 of them and WHERE country <> 'IN' returns 60. Where are the other 10?
Answer
Their country is NULL. For those rows, both country = 'IN' and country <> 'IN' are unknown, so neither query returns them. WHERE country IS NULL would return exactly those 10 rows. To include them with the non-Indian customers, write WHERE country <> 'IN' OR country IS NULL, or WHERE country IS DISTINCT FROM 'IN'.
What does each expression evaluate to: NULL AND FALSE, NULL OR TRUE, NULL AND TRUE, NOT (NULL = NULL)?
Answer
NULL AND FALSEis false, because false wins inAND.NULL OR TRUEis true, because true wins inOR.NULL AND TRUEis unknown (NULL).NOT (NULL = NULL):NULL = NULLis unknown, andNOT unknownis unknown.
The average rating of a product is computed with AVG(rating). Three customers rated it 4, 5 and 3, and seven customers bought it without rating it (their rating is NULL). What does AVG(rating) return, and what would AVG(COALESCE(rating, 0)) return? Which is right?
Answer
AVG(rating) ignores the NULLs and returns (4 + 5 + 3) / 3 = 4. AVG(COALESCE(rating, 0)) treats the seven missing ratings as zeros and returns 12 / 10 = 1.2.
The first answers "what's the average rating among people who rated it?", which is what a rating display needs. The second claims seven people gave a rating of zero, which isn't true. Substituting zero for NULL changes the question, so only do it when zero is genuinely the right value.
Write a condition that's true when a customer's email changed between two tables, old_c and new_c, including when it changed from NULL to a value or from a value to NULL.
Answer
WHERE old_c.email IS DISTINCT FROM new_c.email
old_c.email <> new_c.email would miss both kinds of change involving a NULL, because those comparisons are unknown. In MySQL, write NOT (old_c.email <=> new_c.email). In Oracle, write (old_c.email <> new_c.email OR (old_c.email IS NULL AND new_c.email IS NOT NULL) OR (old_c.email IS NOT NULL AND new_c.email IS NULL)).
Previous: SQL IN, BETWEEN and LIKE: Lists, Ranges and Pattern Matching
Next: Sorting With ORDER BY: Multiple Keys, Expressions, NULLs and Custom Orders

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.