Conditional IF function
In the previous lesson, we looked at the CASE statement for implementing conditional logic in SQL. However, this is not the only mechanism by which it is possible to implement logic branching in a query. It's time to turn our attention to the IF function.
IF Syntax
IF(condition, value_if_true, value_if_false)- condition
- The logical expression being checked, for example price > 100.
- value_if_true
- The value IF returns if the condition is true.
- value_if_false
The value IF returns if the condition is false or NULL.
Examples
-
Simple comparison of two numbers. Since 10 is not greater than 20, the function will return 'FALSE'.
MySQL 8.4SELECT IF(10>20, "TRUE", "FALSE");
-
Example of use with a real database. Based on the price, it is necessary to determine whether the housing belongs to one of two classes: "Comfort class" and "Economy class". If the price is greater than or equal to 150, then this housing belongs to "Comfort class".
MySQL 8.4SELECT id, price, IF(price >= 150, "Comfort class", "Economy class") AS category FROM Rooms
-
IF functions can also be nested within each other, emulating the CASE operator.
MySQL 8.4SELECT id, price, IF(price >= 200, "Business Class", IF(price >= 150, "Comfort class", "Economy class")) AS category FROM Rooms
IFNULL and NULLIF functions
In addition to the IF function, MySQL also has simpler, but less universal functions IFNULL and NULLIF, aimed at processing NULL values.
IFNULL syntax
IFNULL(value, alternative_value)- value
The value being checked, for example a column that may contain NULL. If it is not NULL, the function returns it.
- alternative_value
The value the function returns if value is NULL.
-
If the first argument is not equal to NULL, then it will be returned.
MySQL 8.4SELECT IFNULL("RianAcademy", "Alternative RianAcademy") AS sql_trainer;
-
If the first argument is equal to NULL, then the value passed by the second argument will be returned.
MySQL 8.4SELECT IFNULL(NULL, "Alternative RianAcademy") AS sql_trainer;
NULLIF syntax
NULLIF(value_1, value_2)- value_1
The value the function returns if it is not equal to value_2.
- value_2
The value to compare with. If value_1 equals it, the function returns NULL.
Examples with the NULLIF function
-
If the value of the first argument is equal to the value of the second argument, then NULL is returned.
MySQL 8.4SELECT NULLIF("RianAcademy", "RianAcademy") AS sql_trainer;
-
If the values of the first and second arguments are different, then the value of the first argument is returned.
MySQL 8.4SELECT NULLIF("RianAcademy", "Alternative RianAcademy") AS sql_trainer;