NULL is SQL's way of saying "I do not know" or "this value is missing." It is not the same as zero or an empty string. NULL means no value exists.
And here is the thing โ you cannot check for NULL using = NULL.
That will not work. You have to use IS NULL or IS NOT NULL.
IS NULL
First, let us add a student with a missing value so we have something to work with:
INSERT INTO students VALUES (6, 'Unknown', NULL, NULL, NULL);
SELECT * FROM students WHERE age IS NULL;
IS NOT NULL
-- Only students who have an age recorded
SELECT * FROM students WHERE age IS NOT NULL;
The NULL Trap
This is one of the most important things to understand about NULL. Any operation involving NULL gives you NULL:
SELECT NULL + 5; -- NULL
SELECT NULL = NULL; -- NULL (not true!)
SELECT NULL AND TRUE; -- NULL
NULL = NULL is not true. It is NULL, which means "unknown."
If I ask you "does the unknown value equal the other unknown value?"
you cannot answer yes or no. That is why you must use IS NULL
instead of = NULL.
This trips up everyone. And I mean everyone. Even experienced developers
occasionally forget and write WHERE column = NULL. If your query
returns zero results and you expected some, check for this.