Sub topic 8
Why rows with NULL keys disappear
This chapter assumes you can write a basic SELECT with WHERE and ORDER BY, and that you know what a primary key and a foreign key are. It also assumes you have seen the INNER JOIN ... ON syntax. Here you will learn why rows whose join column is NULL never appear in an inner join result, how to confirm that this is what happened, and what to do when you need those rows.
The examples use the customers and orders tables from earlier in this tutorial. Order 104 has a NULL in customer_id, and Chloe has no orders.
NULL means "unknown", not "empty"
NULL is a marker for a missing or unknown value. It is not zero, and it is not an empty string. Because the value is unknown, SQL cannot say whether it equals anything else, including another NULL.
SQL handles this with three-valued logic. A comparison can evaluate to one of three results: TRUE, FALSE, or UNKNOWN. Any comparison that involves NULL evaluates to UNKNOWN.
| Expression | Result |
|---|---|
| `1 = 1` | TRUE |
| `1 = 2` | FALSE |
| `NULL = 1` | UNKNOWN |
| `NULL = NULL` | UNKNOWN |
| `NULL <> 1` | UNKNOWN |
| `NULL IS NULL` | TRUE |
The surprising rows are NULL = NULL and NULL <> 1. Neither is true, and neither is false. Both are unknown.
How the ON clause treats UNKNOWN
An inner join keeps a pair of rows only when the ON condition evaluates to TRUE. Rows where the condition is FALSE are dropped. Rows where it is UNKNOWN are dropped too.
Take the join from earlier chapters:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id;For order 104, o.customer_id is NULL. The database evaluates NULL = 1, NULL = 2, and NULL = 3 against each customer. All three are UNKNOWN, so order 104 pairs with no customer and is excluded. The query returns three rows. Order 104 is not in them.
The same happens in the other direction for Chloe, but for a different reason. Chloe's id is 3, which is not NULL. No order has customer_id = 3, so every comparison is simply FALSE. Both rows disappear, but only order 104 disappears because of NULL.
Two NULLs never match each other
A common assumption is that two NULL values in matching columns will pair up. They do not. Suppose both tables had a nullable region column:
SELECT a.id, b.id
FROM accounts AS a
INNER JOIN branches AS b
ON a.region = b.region;If a.region and b.region are both NULL, then NULL = NULL is UNKNOWN, and that pair is dropped. Rows with a NULL region on either side never appear in this result.
Seeing the dropped rows
To check whether NULL keys are the reason rows are missing, look for them directly. Use IS NULL, which is the only reliable way to test for NULL:
SELECT id, order_date, total
FROM orders
WHERE customer_id IS NULL;This returns order 104. Writing WHERE customer_id = NULL returns nothing, because that comparison is UNKNOWN for every row.
To count how many rows an inner join silently loses, compare the table's row count with the number of matched rows:
SELECT
(SELECT COUNT(*) FROM orders) AS all_orders,
(SELECT COUNT(*)
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id) AS matched_orders;With the sample data this gives 4 and 3. The difference of 1 is order 104.
Rows can be missing for two other reasons, and IS NULL will not find them. The first is a foreign key value with no parent, which a foreign key constraint normally prevents. The second is a row that the WHERE clause removed. Check each cause separately.
Where NULLs come from
Knowing the common sources helps you predict the problem before it happens:
- A foreign key column that allows
NULL, used to mean "no related row yet", such as an order not yet assigned to a customer. - Optional relationships, such as an employee with no manager.
- Data loaded from files or other systems where blank fields became
NULL. - A column produced by an earlier outer join or expression, such as
NULLIFor aCASEwithout anELSE.
A NOT NULL constraint on the foreign key column removes the first source. In the sample schema, orders.customer_id allows NULL, which is why order 104 can exist.
NULLs in WHERE after a join
The same rule applies to WHERE. A row is kept only if the condition is TRUE. This catches people when they filter with <>:
SELECT id, customer_id
FROM orders
WHERE customer_id <> 1;This returns order 103 only. Order 104 is not returned, even though its customer is "not 1". The comparison NULL <> 1 is UNKNOWN, so the row is filtered out. To include it, write the intent explicitly:
SELECT id, customer_id
FROM orders
WHERE customer_id <> 1 OR customer_id IS NULL;Keeping the unmatched rows
If the question requires rows without a match, an inner join is the wrong tool. An outer join keeps unmatched rows and fills the missing side with NULL. A later chapter covers it in detail. This short example keeps order 104:
SELECT o.id AS order_id, c.name
FROM orders AS o
LEFT JOIN customers AS c
ON c.id = o.customer_id;Order 104 now appears with NULL in the name column.
Do not try to patch an inner join with COALESCE in the ON clause, for example ON COALESCE(o.customer_id, 0) = COALESCE(c.id, 0). It can force NULL keys to match, but it replaces missing data with a made-up value, and it often prevents the database from using an index on the join column.
If you truly need NULL to match NULL, some databases offer a null-safe comparison. PostgreSQL and SQL Server 2022 support IS NOT DISTINCT FROM, and MySQL has the <=> operator. Check your database's documentation before relying on either.
Common mistakes
- Expecting
NULL = NULLto be true in anONcondition. - Testing for
NULLwith= NULLinstead ofIS NULL. - Assuming that a smaller result than expected means a bug in the query, when the data holds
NULLkeys. - Using
<>orNOT INin a filter and losing rows whose column isNULL. - Joining on a nullable column and not checking how many rows have
NULLin it.
Exercise
The table orders has 4 rows, and exactly one of them has customerid = NULL. You run SELECT o.id FROM orders AS o INNER JOIN customers AS c ON c.id = o.customerid; and get 3 rows. Then you add a second order with customer_id = NULL. How many rows does the same query return now, and why? What change to the query would make both NULL-keyed orders appear?
Show answer
It still returns 3 rows. Each NULL-keyed order produces only UNKNOWN comparisons against every customer id, and an inner join keeps a pair only when the ON condition is TRUE. To make the NULL-keyed orders appear, use a LEFT JOIN from orders to customers: FROM orders AS o LEFT JOIN customers AS c ON c.id = o.customer_id. Both orders then appear with NULL in the customer columns.
Exercise
Which of these WHERE clauses returns order 104, whose customerid is NULL? (a) WHERE customerid = NULL (b) WHERE customerid IS NULL (c) WHERE customerid <> 1 (d) WHERE customerid = customerid
Show answer
Only (b). In (a), (c) and (d) the comparison involving NULL evaluates to UNKNOWN, so the row is filtered out. IS NULL is the one test that returns TRUE for a NULL value.