NULLIF() in MySQL — How It Works
What the MySQL NULLIF() function does, with an example.
Published October 22, 2026
NULLIF(a, b) returns NULL if a equals b, otherwise a. It is commonly used to avoid divide-by-zero errors.
How it works
Combine with IFNULL or COALESCE to supply defaults.
Try it in MySQL
SELECT NULLIF(5, 5)
NULL
SELECT NULLIF(5, 3)
5
SELECT total / NULLIF(count, 0) FROM stats
NULL instead of error
Practical examples
Example 1
SELECT NULLIF(5, 5);
-- NULLExample 2
SELECT NULLIF(5, 3);
-- 5Example 3
SELECT total / NULLIF(count, 0) FROM stats;
-- NULL instead of errorUse it in a real query
SELECT id, NULLIF(5, 5) AS result
FROM your_table
LIMIT 10;Common mistakes
- Forgetting division by zero returns NULL in MySQL, an error in others.
- Using NULLIF on different types.
- Misreading it as the opposite of IFNULL.
Key takeaways
- NULLIF() in one line: NULLIF(a, b) returns NULL if a equals b, otherwise a.
- Try queries in a test database first.
- Check NULL handling and data types.
FAQ
Safe division?
a / NULLIF(b, 0).
Does NULLIF() work in other databases?
Most have an equivalent, but names and syntax vary between MySQL, PostgreSQL, SQL Server and SQLite.