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.
Syntax
IF(conditional_expression, value_under_true_condition, value_on_false_condition);
The IF function looks at the truth of the conditional expression and, depending on this truth, returns either the value passed in the second argument or the third argument.
Examples
-
Simple example
SELECT IF(10>20, "TRUE", "FALSE");
-
Example of use with a real database
SELECT id, price, IF(price >= 150, "Comfort class", "Economy class") AS category FROM Rooms
-
IF functions can also be nested
SELECT 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, SQL also has simpler, but less universal functions IFNULL and NULLIF, aimed at processing NULL values.
IFNULL syntax
IFNULL(value, alternative_value);
The 'IFNULLfunction returns thevaluepassed by the first argument if it is not equal toNULL', otherwise it returns an `alternative_value'.
Examples with the IFNULL function
-
If the first argument is not NULL, then it will be returned.
SELECT IFNULL("SQL Academy", "Alternative SQL Academy") AS sql_trainer;
-
If the first argument is NULL, the value passed by the second argument will be returned.
SELECT IFNULL(NULL, "Alternative SQL Academy") AS sql_trainer;
NULLIF syntax
NULLIF(value_1, value_2);
The NULLIF function returns NULL if value_1 is equal to value_2', otherwise it returns value_1'.
Examples with the NULLIF function
-
If the value of the first argument is equal to the value of the second argument, NULL is returned.
SELECT NULLIF("SQL Academy", "SQL Academy") AS sql_trainer;
-
If the values of the first and second arguments are different, the value of the first argument is returned.
SELECT NULLIF("SQL Academy", 'Alternative SQL Academy") AS sql_trainer;