Lesson

MySQL IFNULL() Function

10 min reading
Free Course

MySQL IFNULL() Function

The MySQL IFNULL() function checks whether the first expression is NULL. It returns the first expression when it is non-NULL, or returns the second fallback expression when the first is NULL.

Syntax

IFNULL(expr1, expr2)
  • expr1: The expression or column to test for NULL.
  • expr2: The fallback value returned only when expr1 IS NULL.

IFNULL() is a MySQL-specific function (also supported in SQLite) that accepts exactly two arguments and evaluates expr2 only if expr1 is NULL.

Practical Example

In demo_orders, some orders have no discount_amount recorded (NULL). Using IFNULL(discount_amount, 0) keeps subtraction accurate instead of turning the final price into NULL.

SELECT
    order_id,
    subtotal,
    IFNULL(discount_amount, 0.00) AS applied_discount,
    subtotal - IFNULL(discount_amount, 0.00) AS net_total
FROM demo_orders
ORDER BY order_id;
order_id subtotal applied_discount net_total
1001 200.00 20.00 180.00
1002 85.00 0.00 85.00
1003 150.00 0.00 150.00

Common Mistakes & NULL Behavior

  • Exact NULL behavior: IFNULL(expr1, expr2) does not return NULL just because expr1 is NULL—its job is replacing NULL! It returns NULL only when both expr1 and expr2 are NULL.
  • Empty strings pass through: IFNULL('', 'Default') returns '' because an empty string is not NULL. Use IFNULL(NULLIF(col, ''), 'Default') if blanks should also trigger the fallback.
  • Two-argument limit: Passing three arguments (IFNULL(a, b, c)) causes a syntax error. Use COALESCE(a, b, c) whenever you have multiple fallbacks.
  • SQL Server confusion: In SQL Server, ISNULL(a, b) does what MySQL's IFNULL(a, b) does, whereas MySQL's ISNULL(a) takes one argument and returns 1 or 0.

Frequently Asked Questions

Does IFNULL() return NULL if the first argument is NULL?

No. When the first argument is NULL, IFNULL() returns its second argument. It returns NULL only if both arguments are NULL.

What is the difference between IFNULL() and COALESCE() in MySQL?

IFNULL() accepts exactly two arguments and is MySQL-specific, while COALESCE() is ANSI SQL and accepts two or more arguments.

Does IFNULL() work on numbers and dates?

Yes. IFNULL(shipped_at, NOW()) and IFNULL(tax, 0) both work cleanly, returning the most general compatible type of the two arguments.

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