Lesson

MySQL NULLIF() Function

10 min reading
Free Course

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 when expr1 != expr2.
  • expr2: The sentinel value to convert into NULL when 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) returns NULL (because expr1 is NULL, not because NULL = NULL is true). NULLIF('abc', NULL) returns 'abc' because 'abc' = NULL is unknown, not true.
  • Case-insensitive string equality: Under default _ci collations, NULLIF('NA', 'na') returns NULL because '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', so NULLIF('a ', 'a') may return NULL.
  • Side effects in expr1: Because MySQL may evaluate expr1 twice internally (once for comparison and once for return), avoid non-deterministic expressions like NULLIF(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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum