MySQL NULLIF() Function
MySQL NULLIF() Function
The MySQL NULLIF() function compares two expressions and returns NULL if they are equal. If they are not equal (or if the second expression is NULL), it returns the first expression unchanged.
Syntax
NULLIF(expr1, expr2)
expr1: The primary expression returned whenexpr1 != expr2.expr2: The sentinel value to convert intoNULLwhen matched.
NULLIF(expr1, expr2) behaves identically to CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END, except expr1 may be evaluated twice in some expressions.
Practical Example
Two classic production uses in demo_orders and demo_customers are turning 0 into NULL before division to prevent divide-by-zero errors, and turning blank strings '' into NULL before COALESCE().
SELECT
order_id,
revenue,
item_count,
revenue / NULLIF(item_count, 0) AS avg_item_price,
COALESCE(NULLIF(coupon_code, ''), 'NO_COUPON') AS normalized_coupon
FROM demo_orders
ORDER BY order_id;
| order_id | revenue | item_count | avg_item_price | normalized_coupon |
|---|---|---|---|---|
| 1001 | 150.00 | 3 | 50.000000 | SAVE10 |
| 1002 | 0.00 | 0 | NULL | NO_COUPON |
| 1003 | 90.00 | 2 | 45.000000 | NO_COUPON |
Common Mistakes & NULL Behavior
- Exact NULL behavior:
NULLIF(NULL, NULL)returnsNULL(becauseexpr1isNULL, not becauseNULL = NULLis true).NULLIF('abc', NULL)returns'abc'because'abc' = NULLis unknown, not true. - Case-insensitive string equality: Under default
_cicollations,NULLIF('NA', 'na')returnsNULLbecause'NA' = 'na'is true. Cast or specify collation if you need a case-sensitive check. - Trailing spaces in comparisons: Under PAD SPACE collations,
'a 'equals'a', soNULLIF('a ', 'a')may returnNULL. - Side effects in
expr1: Because MySQL may evaluateexpr1twice internally (once for comparison and once for return), avoid non-deterministic expressions likeNULLIF(RAND(), 0).
Frequently Asked Questions
How does NULLIF() prevent division by zero in MySQL?
Divide by NULLIF(denominator, 0). When denominator is 0, NULLIF() returns NULL, and dividing any number by NULL safely yields NULL instead of an error or warning.
How is NULLIF() different from IFNULL()?
They do opposite jobs: NULLIF(a, b) creates NULL when a = b, while IFNULL(a, b) replaces NULL with b when a IS NULL.
Can NULLIF() convert empty strings to NULL?
Yes. NULLIF(TRIM(column_name), '') converts both empty and whitespace-only strings into NULL.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.