Techniques and functions to detect, compare, and substitute NULL values in MySQL queries.
NULL represents "unknown" data. Any arithmetic or comparison with NULL returns NULL, so special operators and functions are required to test or replace it.
Use IS NULL
and IS NOT NULL
.Ordinary =
and !=
never match NULL.
SELECT id, name FROM Customers WHERE email IS NULL;
Use NULL-safe equal <=>
to return TRUE when both sides are NULL.
SELECT * FROM Products p WHERE p.price <=> NULL;
— returns rows where price
is NULL.
IFNULL(expr, alt)
and COALESCE(expr1, ...)
return the first non-NULL argument.
SELECT id, IFNULL(email, 'no-email@example.com') AS safe_email FROM Customers;
Wrap denominators with COALESCE(denominator,1)
to avoid NULL dividers.
NULLIF
useful?NULLIF(a,b)
returns NULL when a=b
; otherwise it returns a
.Great for turning zero into NULL before aggregation.
SELECT NULLIF(stock,0) AS stock_or_null FROM Products;
Prefer COALESCE
for multiple fallbacks, avoid = NULL
, and store defaults in schema when possible.
Yes. Use COUNT(column)
to ignore NULLs or COUNT(*)
to include them. Combine with WHERE column IS NOT NULL
for clarity.
.
Yes. MySQL evaluates arguments left to right and returns the first non-NULL, making it efficient for multiple fallbacks.
IFNULL accepts exactly two arguments and has identical performance to COALESCE with two parameters. Choose based on readability.
Yes. MySQL can use B-tree indexes to locate NULL values efficiently when the indexed column allows NULLs.