This tutorial explains how to use the MySQL IF function with syntax and examples.
The MySQL IF function returns one value if a condition evaluates to TRUE, or another value if it evaluates to FALSE.
The syntax for the IF function in MySQL is:
The value that you want to test.
Optional. It is the value that is returned if condition evaluates to TRUE.
Optional. It is the value that is return if condition evaluates to FALSE.
The IF function can be used in the following versions of MySQL:
Let's look at some MySQL IF function examples and explore how to use the IF function in MySQL.
This first IF function example shows how you would return a string value.
For example:
In this IF function example, the condition is 100200. If this condition is TRUE, the IF function will return 'yes'. Otherwise, the IF function will return 'no'.
The first IF function example uses a numeric condition. However, you can also use the IF function with a string condition.
For example:
In this IF function example, the condition uses the STRCMP function to compare 2 strings: STRCMP('AODBA.com','mysite.com').
If the string 'AODBA.com' is the same as the string 'mysite.com', the IF function will return 'yes'. Otherwise, the IF function will return 'no'.
This next IF function example shows how you would return a numeric value.
For example:
In this IF function example, the condition is 100200. If this condition is TRUE, the IF function will return the numeric value 5000. Otherwise, if the condition is FALSE, the IF function will return 6000.
Let's look at an example that uses the IF function to test the value of a field in a table.
For example:
In this IF function example, the IF function tests the value of the quantity field in the suppliers table. The IF function will evaluate the condition, quantity>10, for each row in our result set.
So (for each row) if quantity>10, the IF function will return 'More'. Otherwise, the IF function will return 'Less'.