Sub topic 4
Testing for NULL with IS NULL and IS DISTINCT FROM
Assume you already know basic SELECT, WHERE, ORDER BY, joins, and GROUP BY. This chapter focuses on choosing the correct predicate when a column may contain NULL.
NULL does not mean zero, an empty string, or FALSE. It means that a value is missing, unknown, or not applicable. Because it is not an ordinary value, use special tests to detect it.
Use IS NULL and IS NOT NULL
The IS NULL predicate is TRUE when a value is NULL. The IS NOT NULL predicate is TRUE when a value is present.
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);
-- Find employees without a recorded commission.
SELECT name
FROM employees
WHERE commission IS NULL;
-- Find employees with a recorded commission.
SELECT name, commission
FROM employees
WHERE commission IS NOT NULL;The first query returns Ada and Cy. The second returns Ben and Di.
Do not write commission = NULL. SQL comparisons with NULL produce UNKNOWN, not TRUE. A WHERE clause keeps only rows for which its condition is TRUE, so = NULL matches no rows.
| Predicate | Meaning |
|---|---|
| `value IS NULL` | The value is missing or unknown |
| `value IS NOT NULL` | The value is present |
| `value = NULL` | `UNKNOWN`, so it does not find nulls |
Compare values safely with IS DISTINCT FROM
Sometimes you need to compare two expressions while treating NULL as a comparable state. IS DISTINCT FROM returns a definite Boolean result:
- It returns
FALSEwhen both values are equal. - It returns
FALSEwhen both values areNULL. - It returns
TRUEwhen exactly one value isNULL. - Otherwise, it behaves like inequality.
IS NOT DISTINCT FROM is the opposite. It treats two NULL values as equal.
-- Returns Ada, Cy, and Di.
-- Their commission is distinct from 100.
SELECT name
FROM employees
WHERE commission IS DISTINCT FROM 100;
-- Returns rows where the commission is 100,
-- or where both compared expressions are NULL.
SELECT name
FROM employees
WHERE commission IS NOT DISTINCT FROM 100;The second query returns Ben only in this sample. Ada and Cy have NULL, while 100 is not NULL, so those values are distinct.
IS DISTINCT FROM is available in PostgreSQL and several other systems, but support and spelling differ. MySQL commonly uses the null-safe equality operator <=>. Check your database documentation before using it in portable application SQL.
Exercise
What does this query return, and why? SELECT name FROM employees WHERE commission IS DISTINCT FROM NULL;
Show answer
It returns Ben and Di. A non-NULL value is distinct from NULL, while Ada and Cy have NULL values and are not distinct from NULL.