MySQL IFNULL() Function
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 forNULL.expr2: The fallback value returned only whenexpr1 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 returnNULLjust becauseexpr1isNULL—its job is replacingNULL! It returnsNULLonly when bothexpr1andexpr2areNULL. - Empty strings pass through:
IFNULL('', 'Default')returns''because an empty string is notNULL. UseIFNULL(NULLIF(col, ''), 'Default')if blanks should also trigger the fallback. - Two-argument limit: Passing three arguments (
IFNULL(a, b, c)) causes a syntax error. UseCOALESCE(a, b, c)whenever you have multiple fallbacks. - SQL Server confusion: In SQL Server,
ISNULL(a, b)does what MySQL'sIFNULL(a, b)does, whereas MySQL'sISNULL(a)takes one argument and returns1or0.
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.
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.