Sub topic 3
Why = NULL Never Matches
Assume you know basic SELECT, WHERE, and comparisons. This chapter uses a small employees table to show why NULL needs special syntax.
`NULL` Is Not an Ordinary Value
NULL represents a missing, unknown, or inapplicable value. It is different from:
0, which is a known number.'', which is a known empty string.FALSE, which is a known boolean value.
For example, an employee may have no commission because the commission has not been recorded. The database stores that absence as NULL.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
commission NUMERIC(8, 2)
);
INSERT INTO employees (id, name, commission) VALUES
(1, 'Ada', NULL),
(2, 'Ben', 100.00),
(3, 'Cy', NULL),
(4, 'Di', 300.00);
-- This returns no rows.
SELECT name
FROM employees
WHERE commission = NULL;
-- This returns Ada and Cy.
SELECT name
FROM employees
WHERE commission IS NULL;Why the Comparison Is Unknown
SQL uses three-valued logic for expressions involving NULL:
TRUEFALSEUNKNOWN
A comparison with an unknown value cannot produce a reliable true or false result. Therefore, commission = NULL evaluates to UNKNOWN, not TRUE, even when commission itself is NULL.
The same rule applies to other comparison operators:
commission = NULL
commission <> NULL
commission > NULL
commission <= NULLEach expression evaluates to UNKNOWN.
A WHERE clause keeps only rows for which its condition is TRUE. It removes rows where the condition is FALSE or UNKNOWN.
flowchart TD
A["commission = NULL"] --> B["UNKNOWN"]
B --> C{"WHERE keeps TRUE?"}
C -->|No| D["Row is filtered out"]
C -->|Yes| E["Row is returned"]Use `IS NULL` for Missing Values
IS NULL is a null test, not an ordinary comparison. It returns TRUE when the expression is NULL and FALSE otherwise.
SELECT name
FROM employees
WHERE commission IS NULL;
SELECT name
FROM employees
WHERE commission IS NOT NULL;The first query returns Ada and Cy. The second returns Ben and Di.
You can combine these tests with other conditions:
SELECT name
FROM employees
WHERE commission IS NULL OR commission > 200;This returns Ada, Cy, and Di. The IS NULL condition explicitly handles rows with no commission.
A Null-Safe Inequality
Some database systems, including PostgreSQL, support IS DISTINCT FROM. It treats two NULL values as equal and treats a NULL value as different from every non-NULL value.
-- PostgreSQL and some other systems
SELECT name
FROM employees
WHERE commission IS DISTINCT FROM 100;This returns Ada, Cy, and Di. Check your database documentation before using this syntax because support varies.
Exercise
What does this query return, and why? SELECT name FROM employees WHERE commission <> 100;
Show answer
It returns only Di. Ben is excluded because his commission is 100, while Ada and Cy are excluded because comparing NULL with 100 produces UNKNOWN. WHERE keeps only TRUE.