How to Use IF Function in MySQL: Syntax and Examples
In MySQL, the
IF function lets you return one value if a condition is true and another if it is false. Its syntax is IF(condition, value_if_true, value_if_false). Use it to add simple conditional logic inside your queries.Syntax
The IF function in MySQL has three parts:
- condition: A test that returns true or false.
- value_if_true: The value returned if the condition is true.
- value_if_false: The value returned if the condition is false.
This function helps you choose between two values based on a condition.
sql
IF(condition, value_if_true, value_if_false)
Example
This example shows how to use IF to label ages as 'Adult' or 'Minor' in a table called people:
sql
SELECT name, age, IF(age >= 18, 'Adult', 'Minor') AS age_group FROM people;
Output
name | age | age_group
-----|-----|----------
John | 20 | Adult
Amy | 15 | Minor
Bob | 18 | Adult
Common Pitfalls
Common mistakes when using IF include:
- Forgetting the third argument, which causes errors.
- Using complex conditions without parentheses, leading to wrong results.
- Confusing
IFfunction withIF()statement in procedural code.
Always provide all three parts and test your conditions carefully.
sql
/* Wrong: Missing third argument */ SELECT IF(age >= 18, 'Adult') FROM people; /* Right: Include all three arguments */ SELECT IF(age >= 18, 'Adult', 'Minor') FROM people;
Quick Reference
| Part | Description | Example |
|---|---|---|
| condition | Test that returns true or false | age >= 18 |
| value_if_true | Value if condition is true | 'Adult' |
| value_if_false | Value if condition is false | 'Minor' |
Key Takeaways
Use IF(condition, value_if_true, value_if_false) to add simple conditional logic in MySQL queries.
Always provide all three arguments to avoid errors.
Test your conditions carefully and use parentheses for complex expressions.
IF returns one of two values based on the condition's truth value.
It is useful for labeling or categorizing data directly in SELECT statements.