MySQL IF() Function
MySQL IF() Function
The MySQL IF() function evaluates a single condition and returns one value when the condition is true, or a fallback value when it is false or NULL. It provides a compact inline alternative to a two-branch CASE expression.
Syntax
IF(condition, value_if_true, value_if_false)
condition: Any boolean or numeric expression. Non-zero, non-NULLvalues are treated as true;0andNULLare treated as false.value_if_true: Returned whenconditionis true (<> 0andIS NOT NULL).value_if_false: Returned whenconditionis0orNULL.
Note that the IF() function is distinct from the IF ... THEN ... END IF flow-control statement used inside stored procedures.
Practical Example
In demo_products, flag whether each item is in stock or sold out based on stock_qty.
SELECT
product_id,
product_name,
stock_qty,
IF(stock_qty > 0, 'In Stock', 'Out of Stock') AS availability
FROM demo_products
ORDER BY product_id;
| product_id | product_name | stock_qty | availability |
|---|---|---|---|
| 1 | Mechanical Keyboard | 14 | In Stock |
| 2 | USB-C Hub | 0 | Out of Stock |
| 3 | Monitor Arm | NULL | Out of Stock |
Common Mistakes & NULL Behavior
- NULL condition takes the false branch:
IF(NULL, 'Yes', 'No')returns'No', notNULL! It only returnsNULLif the selected branch (value_if_trueorvalue_if_false) itself evaluates toNULL. - Not standard ANSI SQL: PostgreSQL and SQLite do not have a 3-argument
IF()function (SQLite calls itIIF(), while standard SQL usesCASE WHEN ... THEN ... ELSE ... END). UseCASEif portability matters. - Nested
IF()readability: Chaining three or moreIF()calls inside each other quickly becomes unreadable. Switch toCASE WHEN ...as soon as you need three or more outcomes. - Type mixing: Returning a number in one branch and a string in the other coerces the entire column to string or floating-point depending on the mix.
Frequently Asked Questions
What does MySQL IF() return if the condition is NULL?
MySQL treats a NULL condition as false, so IF(NULL, 'A', 'B') returns 'B' (the third argument).
Is MySQL IF() the same as IFNULL()?
No. IF(cond, a, b) checks any boolean condition, whereas IFNULL(a, b) specifically checks whether a IS NULL and returns a if not NULL or b otherwise.
Can I use IF() inside an aggregate function like SUM()?
Yes. SUM(IF(status = 'paid', 1, 0)) counts matching rows cleanly in MySQL.
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.