← SQL and databases

NULL and IS NULL

Find rows where a value is missing.

Start this lesson

Sometimes a value is unknown or does not exist yet: a member gave no email, a book has not been returned. Databases store this as NULL. NULL is not zero and not empty text; it means "no value". Because of that, a normal comparison like email = NULL is never true. To test for missing values you write IS NULL, and for present values IS NOT NULL.

SELECT id, book_id FROM loans
WHERE returned_date IS NULL;

Loans with no returned date are books still out with a member.

Why is email = NULL never true? Think of NULL as "I don't know". Is an unknown email equal to another unknown? The honest answer is "don't know", and WHERE only keeps rows where the answer is a clear yes.