MySQL NULL Values: Comparisons, Sorting, and Functions
Understand how MySQL treats NULL in comparisons, filters, sorting, grouping, aggregates, unique indexes, and null-handling functions.
In MySQL, NULL means a value is unknown or missing. It is different from zero (0) and from an empty string (''). A column can allow or reject NULL values with its NULL or NOT NULL definition.
Compare values with NULL
Ordinary comparisons that involve NULL evaluate to NULL (unknown), not to TRUE or FALSE. This includes NULL = NULL, so a WHERE column = NULL condition does not find rows with a null value.
SELECT
NULL = NULL AS ordinary_equality,
NULL <=> NULL AS null_safe_equality,
NULL IS NULL AS is_null;
+-------------------+--------------------+---------+
| ordinary_equality | null_safe_equality | is_null |
+-------------------+--------------------+---------+
| NULL | 1 | 1 |
+-------------------+--------------------+---------+Use IS NULL or IS NOT NULL to filter for missing or present values. MySQL’s <=> operator is null-safe equality: it returns 1 when both operands are NULL and 0 when only one is NULL.
NULL in sorting, grouping, and aggregates
- In ascending
ORDER BY, MySQL sortsNULLvalues first; in descending order, it sorts them last. GROUP BYtreatsNULLvalues as equal and places them in the same group.- Aggregate functions such as
SUM()andAVG()ignoreNULLinputs.COUNT(column)counts non-NULLvalues, whileCOUNT(*)counts rows. - A MySQL
UNIQUEindex treatsNULLvalues as distinct by default, so it permits multipleNULLvalues. See the MySQL unique index guide.
These rules can affect the result even when no query syntax error occurs. For example, WHERE amount <> 0 does not include rows where amount is NULL; add OR amount IS NULL if those rows should be included.
Replace or compare missing values
Use a null-handling function when a query needs a substitute or fallback value:
SELECT IFNULL(phone, 'N/A') AS phone_display;
SELECT COALESCE(phone, email, 'N/A') AS contact;
SELECT NULLIF('', '') AS empty_as_null;
IFNULL(value, replacement)returns the replacement whenvalueisNULL.COALESCE(value1, value2, ...)returns the first non-NULLargument.NULLIF(value1, value2)returnsNULLwhen the two arguments are equal; otherwise it returnsvalue1.
For the complete COALESCE() reference, see the MySQL COALESCE() function page. This tutorial also covers the common IFNULL() and NULLIF() patterns above.
For the comparison operators, see MySQL’s official comparison operator documentation. For additional examples of finding NULL values, see the MySQL IS NULL tutorial.