SQL reference (MySQL and MariaDB dialects)

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#

WhereRuleExample
Comparison=, <>, <, >, LIKE, IN ... with NULL give NULL (unknown)SELECT NULL = NULL is NULL
Null-safe comparison<=> is true when both sides are NULL or equalSELECT 1 <=> NULL is 0, NULL <=> NULL is 1
TestIS NULL, IS NOT NULL, ISNULL(x)SELECT NULL IS NULL is 1
Logicthree-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
WHEREa row is kept only if the condition is true; unknown rows are droppedWHERE n > 1 drops rows where n is NULL
IS TRUE, IS FALSE, IS UNKNOWNalways 0 or 1, never NULLNULL IS UNKNOWN is 1
Arithmeticany NULL operand gives NULL; so does division by zero1 + NULL, 1 / 0
Bit operatorsa NULL operand gives NULLNULL & 1
Functionsmost 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, COUNTCONCAT('a', NULL) is NULL, CONCAT_WS(',', 'a', NULL, 'c') is a,c
AggregatesCOUNT(*) counts rows; the other aggregates ignore NULL; over no values COUNT is 0 and the others are NULLSUM(n) over a group with only NULL is NULL
GROUP BY, DISTINCTall NULLs are one group / one value
ORDER BYNULL sorts first in ASC order and last in DESC order
NOT NULL columnan insert or update that stores NULL is refused with error 1048 (A NULL value cannot be stored in column 'x')
MIN, MAX, GREATEST, LEASTGREATEST and LEAST give NULL if any argument is NULL; MIN and MAX ignore NULL

Remarks#

  • x IN (1, NULL) is true if x is 1 and NULL otherwise (never false); x NOT IN (1, NULL) is never true. The same holds for NOT IN (subquery) when the subquery returns a NULL.
  • ANY and ALL follow the same three-valued rules; an empty subquery makes ANY false and ALL true.
  • Comparing with NULL in WHERE col = NULL finds nothing: write col IS NULL.
  • In ORDER BY Raft DB orders NULL before 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#

SQL
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

See also#