IF() in MySQL — How It Works

What the MySQL IF() function does, with an example.

Published October 22, 2026

IF(condition, a, b) returns a when the condition is true and b otherwise. It is MySQL's inline ternary.

How it works

For more than two branches use CASE.

Try it in MySQL

SELECT IF(5 > 3, 'yes', 'no')
yes
SELECT IF(stock > 0, 'In stock', 'Sold out') FROM products
label
SELECT SUM(IF(status='paid', total, 0)) FROM orders
paid total

Practical examples

Example 1

SELECT IF(5 > 3, 'yes', 'no');
-- yes

Example 2

SELECT IF(stock > 0, 'In stock', 'Sold out') FROM products;
-- label

Example 3

SELECT SUM(IF(status='paid', total, 0)) FROM orders;
-- paid total

Use it in a real query

SELECT id, IF(5 > 3, 'yes', 'no') AS result
FROM your_table
LIMIT 10;

Common mistakes

  • Nesting many IFs (use CASE).
  • Treating NULL conditions as true (they are false).
  • Different return types.

Key takeaways

  • IF() in one line: IF(condition, a, b) returns a when the condition is true and b otherwise.
  • Try queries in a test database first.
  • Check NULL handling and data types.

FAQ

IF vs CASE?

IF is a function for two outcomes; CASE handles many.

Does IF() work in other databases?

Most have an equivalent, but names and syntax vary between MySQL, PostgreSQL, SQL Server and SQLite.

More SQL articles