Sub topic 3
Why = NULL Never Matches
This chapter assumes you can write SELECT, WHERE, and basic JOIN queries. It also assumes you know that NULL marks a missing or inapplicable value and that SQL uses three truth values: TRUE, FALSE, and UNKNOWN. The chapter explains why the = operator can't find NULLs and which similar queries fail for the same reason.
The sample table
The examples use the employees table from earlier in this tutorial. Ada has no manager. Ada and Cy have no commission recorded.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INTEGER,
commission NUMERIC(8,2)
);
INSERT INTO employees (id, name, manager_id, commission) VALUES
(1, 'Ada', NULL, NULL),
(2, 'Ben', 1, 100.00),
(3, 'Cy', 1, NULL),
(4, 'Di', 2, 300.00);The problem
A natural first attempt at finding employees with no commission is this query:
SELECT name FROM employees WHERE commission = NULL;It returns no rows, even though Ada and Cy have no commission. The database doesn't raise an error. It reports "zero rows" and the query looks correct, so the bug is easy to miss.
A comparison with NULL is UNKNOWN
NULL isn't a value that can be equal to something. It stands for "no value here", and the reason may be that the value is unknown or that it doesn't apply. SQL therefore can't say whether commission = NULL is true or false for a row. The result of any ordinary comparison that has a NULL operand is UNKNOWN.
This applies to every comparison operator, not only =:
| Expression | Result |
|---|---|
| `5 = NULL` | UNKNOWN |
| `5 <> NULL` | UNKNOWN |
| `NULL = NULL` | UNKNOWN |
| `NULL <> NULL` | UNKNOWN |
| `NULL < 5` | UNKNOWN |
| `NULL IS NULL` | TRUE |
The NULL = NULL row surprises many people. If two values are both unknown, the database can't say whether they are the same. They might be, or they might not. UNKNOWN is the only honest answer.
You can see UNKNOWN directly by putting comparisons in the SELECT list. Most systems display UNKNOWN as NULL, because a boolean that is UNKNOWN is represented as NULL. SQLite and MySQL show TRUE and FALSE as 1 and 0.
SELECT name,
commission,
commission = 100 AS equals_100,
commission <> 100 AS differs_from_100
FROM employees
ORDER BY id;The result:
| name | commission | equals_100 | differs_from_100 |
|---|---|---|---|
| Ada | NULL | NULL | NULL |
| Ben | 100.00 | true | false |
| Cy | NULL | NULL | NULL |
| Di | 300.00 | false | true |
Ada and Cy get UNKNOWN for both comparisons. Neither commission = 100 nor commission <> 100 is true for them.
Why WHERE drops those rows
The WHERE clause evaluates its condition for each row and keeps the row only if the result is TRUE. A row whose condition is FALSE is discarded, and so is a row whose condition is UNKNOWN. There is no third output for "maybe".
This explains the two queries from the problem section. In WHERE commission = NULL, the condition is UNKNOWN for every row, because the right-hand side is always NULL. In the second, the condition is TRUE only for rows where commission is not NULL and differs from 100.
-- Returns only Di: Ada and Cy are UNKNOWN and filtered out.
SELECT name FROM employees WHERE commission <> 100;Many people read <> 100 as "everyone except those with 100". SQL reads it as "rows where commission is known and is not 100". Rows with a NULL commission fall outside both = 100 and <> 100.
The fix: IS NULL
SQL has a separate predicate for testing missing values. IS NULL never returns UNKNOWN. It returns TRUE if the value is NULL and FALSE otherwise.
-- Returns Ada and Cy.
SELECT name FROM employees WHERE commission IS NULL;
-- Returns Ben and Di.
SELECT name FROM employees WHERE commission IS NOT NULL;Never write = NULL or <> NULL. Some tools accept != NULL or == NULL as an extension, but treat that as non-portable and avoid it. MySQL also has a <=> operator that is a NULL-safe equality test, but it isn't standard SQL.
Getting "not equal, or missing"
You often want "everyone whose commission is not 100, including those with no commission". There are two ways to write that. The first spells out both cases:
-- Returns Ada, Cy, and Di.
SELECT name
FROM employees
WHERE commission IS NULL OR commission <> 100;The second uses the NULL-safe inequality IS DISTINCT FROM, which treats NULL as an ordinary comparable value:
-- Standard SQL (for example PostgreSQL): returns Ada, Cy, and Di.
SELECT name FROM employees WHERE commission IS DISTINCT FROM 100;IS DISTINCT FROM is standard SQL but isn't available everywhere, so check your system's documentation. Where it's missing, use the IS NULL OR ... form.
The same trap in other places
The rule that a comparison with NULL is UNKNOWN shows up in several constructs. These are the ones that cause the most bugs.
Negation does not rescue you
NOT UNKNOWN is still UNKNOWN. Wrapping a comparison in NOT therefore doesn't recover the NULL rows.
-- Returns only Di. NOT (UNKNOWN) is UNKNOWN, so Ada and Cy are still dropped.
SELECT name FROM employees WHERE NOT (commission = 100);Comparing a column with itself
A column compared with itself isn't always TRUE. For a row where the column is NULL, commission = commission is UNKNOWN.
-- Returns Ben and Di, not all four rows.
SELECT name FROM employees WHERE commission = commission;Equality joins
A join condition is filtered the same way as a WHERE condition. Two NULL keys never match each other. In this self-join on commission, Ada and Cy can't even match themselves:
-- Returns Ben and Di. Ada and Cy are missing from the result.
SELECT e.name
FROM employees e
JOIN employees m ON m.commission = e.commission
ORDER BY e.name;If you want NULL keys to match, use a NULL-safe comparison in the ON clause, such as e.commission IS NOT DISTINCT FROM m.commission where your system supports it. Think carefully before doing this, because it usually isn't what the data model intends.
IN lists that contain NULL
x IN (a, b, NULL) is shorthand for x = a OR x = b OR x = NULL. The last term is UNKNOWN. A match on a or b still gives TRUE, because TRUE OR UNKNOWN is TRUE. A non-match gives UNKNOWN rather than FALSE, because FALSE OR UNKNOWN is UNKNOWN.
-- Returns only Ben. Di is UNKNOWN, not FALSE, and NULL in the list never matches Ada or Cy.
SELECT name FROM employees WHERE commission IN (100, NULL);For plain IN the difference between FALSE and UNKNOWN rarely matters, because both are filtered out. It matters a great deal for NOT IN, where NOT UNKNOWN is UNKNOWN. That case is the subject of its own chapter.
A debugging checklist
When a query returns fewer rows than you expect, work through these questions:
- Which columns in the condition can be NULL? Check the table definition for missing
NOT NULLconstraints. - Is any of them compared with
=,<>,<,>,IN, orNOT IN? Each of those turns a NULL into UNKNOWN. - Do you want the NULL rows in the result? If so, add
OR column IS NULLor useIS DISTINCT FROM. - Is the same column used as a join key? If so, rows with NULL keys have been dropped from the join.
To find out which rows are being lost, select the comparison itself, as in the equals_100 example above. A NULL in that column is a row that WHERE will discard.
Exercises
Exercise
Without running it, predict which names this query returns, and explain why: SELECT name FROM employees WHERE commission = commission;
Show answer
It returns Ben and Di. For Ada and Cy, commission is NULL, so NULL = NULL is UNKNOWN and WHERE discards the row. For Ben and Di the comparison is TRUE.
Exercise
Write a query that returns every employee whose commission is not 300, including those with no commission recorded. Which names does it return?
Show answer
SELECT name FROM employees WHERE commission IS NULL OR commission <> 300; (or WHERE commission IS DISTINCT FROM 300 where supported). It returns Ada, Ben, and Cy. A plain commission <> 300 would return only Ben.