MySQL IF( ) Function
The MySQL IF() function is a control flow function that returns different values based on the result of a condition.
IF() Function in MySQL
The IF() function in MySQL returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that can be either numeric or strings, depending upon the context in which the function is used.
The IF() function accepts one parameter, which is the condition to be evaluated.
Syntax
MySQL IF() function syntax is:
IF(condition, true_value, false_value)
Parameters:
- condition – It is used to specify the condition to be evaluated.
- true_value – It is an optional parameter that is used to specify the value to be returned if the condition evaluates to be true.
- false_value – It is an optional parameter that is used to specify the value to be returned if the condition evaluates to be false.
Supported Versions of MySQL
MySQL IF function is supported by the following version of MySQL:
- MySQL 5.7
- MySQL 5.6
- MySQL 5.5
- MySQL 5.1
- MySQL 5.0
- MySQL 4.1
- MySQL 4.0
- MySQL 3.23
MySQL IF( ) Function Examples
Let’s us look at some examples of the IF function in MySQL. Learning MySQL IF() function with examples, helps in understanding the concepts better.
Example 1
Implementing IF() function on a numeric condition and returning a string value.
SELECT IF(5<12, 'TRUE', 'FALSE');
Output:
TRUE
Example 2
Implementing IF() function with SQL STRCMP function to compare two strings
SELECT IF(STRCMP('w3wiki', 'gfg')=0, 'TRUE', 'FALSE');
Output:
FALSE
Example 3
Implementing IF() function on a numeric condition and returning a numeric value.
SELECT IF(5<12, '1', '0');
Output:
1
Important Points About MySQL IF() Function
- The IF() function returns a value if the condition is TRUE or a different value if the condition is FALSE.
- The IF() function can return values that can be either numeric or strings depending on the context in which the function is used.
- The IF() function is useful for implementing conditional logic directly within a query.
- The IF() function is different from the MySQL IF statement, which is used for executing a set of SQL statements based on a pre-defined condition.