NULL handling
How NULL behaves in comparisons, logic, arithmetic, functions, aggregates, ordering, grouping and indexes.
NULL means a missing or unknown value. It is not 0 and not the empty string.
Rules#
| Where | Rule | Example |
|---|---|---|
| Comparison | =, <>, <, >, LIKE, IN ... with NULL give NULL (unknown) | SELECT NULL = NULL is NULL |
| Null-safe comparison | <=> is true when both sides are NULL or equal | SELECT 1 <=> NULL is 0, NULL <=> NULL is 1 |
| Test | IS NULL, IS NOT NULL, ISNULL(x) | SELECT NULL IS NULL is 1 |
| Logic | three-valued: NULL AND 0 is 0, NULL AND 1 is NULL, NULL OR 1 is 1, NULL OR 0 is NULL, NOT NULL is NULL, NULL XOR x is NULL | |
WHERE | a row is kept only if the condition is true; unknown rows are dropped | WHERE n > 1 drops rows where n is NULL |
IS TRUE, IS FALSE, IS UNKNOWN | always 0 or 1, never NULL | NULL IS UNKNOWN is 1 |
| Arithmetic | any NULL operand gives NULL; so does division by zero | 1 + NULL, 1 / 0 |
| Bit operators | a NULL operand gives NULL | NULL & 1 |
| Functions | most return NULL for a NULL argument. Exceptions: COALESCE, IFNULL, ISNULL, NULLIF, IF, CASE, CONCAT_WS (skips NULL arguments), QUOTE (NULL gives the word NULL), JSON_ARRAYAGG, FIELD, COUNT | CONCAT('a', NULL) is NULL, CONCAT_WS(',', 'a', NULL, 'c') is a,c |
| Aggregates | COUNT(*) counts rows; the other aggregates ignore NULL; over no values COUNT is 0 and the others are NULL | SUM(n) over a group with only NULL is NULL |
GROUP BY, DISTINCT | all NULLs are one group / one value | |
ORDER BY | NULL sorts first in ASC order and last in DESC order | |
NOT NULL column | an insert or update that stores NULL is refused with error 1048 (A NULL value cannot be stored in column 'x') | |
MIN, MAX, GREATEST, LEAST | GREATEST and LEAST give NULL if any argument is NULL; MIN and MAX ignore NULL |
Remarks#
x IN (1, NULL)is true ifxis 1 andNULLotherwise (never false);x NOT IN (1, NULL)is never true. The same holds forNOT IN (subquery)when the subquery returns aNULL.ANYandALLfollow the same three-valued rules; an empty subquery makesANYfalse andALLtrue.- Comparing with
NULLinWHERE col = NULLfinds nothing: writecol IS NULL. - In
ORDER BYRaft DB ordersNULLbefore all values, as MySQL and MariaDB do. - A date column that gets an invalid value in non-strict mode stores the zero date, not
NULL(see SQL modes).
Examples#
SELECT NULL IS NULL, 1 <=> NULL, NULL AND 0, NULL OR 1, CONCAT('a', NULL), COALESCE(NULL, NULL, 3);
SELECT COUNT(n), COUNT(*), SUM(n), AVG(n) FROM words; -- COUNT ignores NULL, COUNT(*) does not
SELECT n FROM words ORDER BY n; -- NULL first
SELECT n FROM words ORDER BY n DESC; -- NULL last