Lesson

MySQL IF() Function

10 min reading
Free Course

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-NULL values are treated as true; 0 and NULL are treated as false.
  • value_if_true: Returned when condition is true (<> 0 and IS NOT NULL).
  • value_if_false: Returned when condition is 0 or NULL.

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', not NULL! It only returns NULL if the selected branch (value_if_true or value_if_false) itself evaluates to NULL.
  • Not standard ANSI SQL: PostgreSQL and SQLite do not have a 3-argument IF() function (SQLite calls it IIF(), while standard SQL uses CASE WHEN ... THEN ... ELSE ... END). Use CASE if portability matters.
  • Nested IF() readability: Chaining three or more IF() calls inside each other quickly becomes unreadable. Switch to CASE 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.

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