IF
has three parameters:
1 - Condition.
2 - Executes if the condition evaluates to
true
3 - Executes if the condition evaluates to
false
IF(condition , [expression when true], [expression when false]);
Returns
false
because the first parameter
0
evaluates to false
SELECT IF(0, 'true', 'false') AS Boolean
Simple
IF
statement in
SELECT
clause
SELECT *,
IF(points>=90, "Brilliant", "Lazy") AS class
FROM `students`
ORDER BY points DESC
Nested IF
conditional statement.
Categorizes students based on their points
SELECT *,
IF(points>=90, "Brilliant", IF(points>=80, "Gold", IF(points>=60, "Silver", "Lazy"))) AS class
FROM `students`
ORDER BY points DESC
Sub-query inside
IF
.
Highlights the student with highest points
SELECT *,
IF(points>=90, IF(points=(SELECT MAX(points) FROM students), "Highest", "Brilliant"), IF(points>=80, "Gold", IF(points>=60, "Silver", "Lazy"))) AS class
FROM `students`
ORDER BY points DESC
IF
statement in
WHERE
clause.
Checks
mail
if it is not empty otherwise checks
mail2
SELECT *
FROM `students`
WHERE IF(LENGTH(mail), mail, mail2) LIKE '%gmail.com%'