SQL NULLIF Function
Quick summary: The SQL NULLIF() function returns NULL if two expressions are equal.
SQL NULLIF Syntax
NULLIF(expression1, expression2)
SQL
SQL NULLIF Basic examples
SELECT NULLIF(0, 0);
SQL
Output:
NULL
Returns NULL when values match.
SQL NULLIF Real-world usage
SELECT total / NULLIF(quantity, 0) FROM orders;
SQL
Output:
Safe division
Prevents division by zero.
SQL NULLIF Edge cases
SELECT NULLIF(5, 3);
SQL
Output:
5
Returns first value when not equal.
SQL NULLIF Common mistakes
Confusing NULLIF with COALESCE
They solve opposite problems.
Incorrect
COALESCE(a, b)
Correct
NULLIF(a, b)
Use NULLIF to nullify values.
SQL NULLIF Frequently Asked Questions
What does NULLIF() do in SQL?
Returns NULL if two expressions are equal.
Use case of NULLIF()?
Avoid division by zero.
Syntax?
NULLIF(value1, value2).
Return type?
Same as first argument.
Common mistake?
Expecting boolean result.
Performance?
Fast.
Alternative?
CASE.
Used in calculations?
Yes.
Handles NULL?
Yes.
Used with COALESCE?
Yes.
Best practice?
Use for safe math.
Used in reports?
Yes.