In this section, we are going to learn how IF() function works in MySQL. The IF function is one of the parts of the MySQL control flow function, which returns a value based on the given conditions. In other words, the IF function is used for validating a function in MySQL. The IF function returns a value YES when the given condition evaluates to true and returns a NO value when the condition evaluates to false. It returns values either in a string or numeric form depending upon the context in which this function is used. Sometimes, this function is known as IF-ELSE and IF THAN ELSE function.
The IF function takes three expressions, where the first expression will be evaluated. If the first expression evaluates to true, not null, and not zero, it returns the second expression. If the result is false, it returns the third expression.
IF ( expression 1, expression 2, expression 3)
Parameter | Requirement | Descriptions |
---|---|---|
Expression 1 | Required | It is a value, which is used for validation. |
Expression 2 | Optional | It returns a value when the condition evaluates to true. |
Expression 3 | Optional | It returns a value when the condition evaluates to false. |
The return type of IF function can be calculated as follows:
The IF function can support the following MySQL versions:
Let us understand the MySQL IF function with the following examples. We can use the IF function with the SELECT statement directly.
SELECT IF(200>350,'YES','NO');
In the above function, the (200>350) is a condition, which is evaluated. If the condition is true, it returns a value, YES, and if the condition is false, it returns NO.
Output:
NO
SELECT IF(251 = 251,' Correct','Wrong');
In the above function, the (251 = 251) is a condition, which is evaluated. If the condition is true, it returns value Correct, and if the condition is false, it returns Wrong output.
Output:
Correct
SELECT IF(STRCMP('Rinky Ponting','Yuvraj Singh')=0, 'Correct', 'Wrong');
The above example compares the two strings. If both the string is the same, it returns Correct. Otherwise, the IF function returns Wrong output.
Output:
Wrong
Here, we are going to create a table 'student' and perform the IF function.
Now, run the following MySQL query. This statement returns the last name of the student table, in which, if the age is greater than 20, it returns Mature. Otherwise, the IF function returns Immature.
SELECT lastname, IF(age>20,"Mature","Immature") As Result FROM student;
Output:
When the above MySQL statement runs successfully, it will give the following output.