Sub topic 1
What NULL Means: Unknown, Missing, or Not Applicable
Prerequisites
This chapter assumes you can write basic SELECT, WHERE, and ORDER BY queries, understand tables, rows, and columns, and have used simple joins and GROUP BY. The examples use this table:
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);What NULL Means
NULL marks a value that is absent. It can mean unknown (a birth date was never recorded), missing (a middle name was not supplied), or not applicable (Ada has no manager).
NULL is not zero, an empty string, or FALSE. Those are real values. NULL means there is no value at all.
Three-Valued Logic: TRUE, FALSE, and UNKNOWN
Ordinary logic has two results. SQL adds a third, UNKNOWN, which comes from comparing with NULL. A WHERE clause keeps a row only when its condition is TRUE.
| Expression | Result |
|---|---|
| NULL = 1 | UNKNOWN |
| NULL AND FALSE | FALSE |
| NULL OR TRUE | TRUE |
| NULL AND TRUE | UNKNOWN |
Why = NULL Never Matches
Because NULL is unknown, SQL cannot say that it equals anything, including another NULL.
-- Returns no rows.
SELECT name FROM employees WHERE commission = NULL;
-- Returns Ada and Cy.
SELECT name FROM employees WHERE commission IS NULL;Testing for NULL with IS NULL and IS DISTINCT FROM
IS NULL and IS NOT NULL test whether a value is present. IS DISTINCT FROM compares two values and treats NULL as a comparable value, so NULL counts as different from 100.
-- Returns Ada, Cy, and Di. Ben is excluded because his commission equals 100.
SELECT name FROM employees WHERE commission IS DISTINCT FROM 100;Exercise
Write a query that returns the names of employees whose commission is missing.
Show answer
SELECT name FROM employees WHERE commission IS NULL; It returns Ada and Cy.