MySQL have several Control Flow Functions listed as below:
1) CASE
2) IF
3) IFNULL
4) NULLIF
Control function returns value based on each row processed by the query executed. Control functions can be used on [code]SELECT[/code], [code]WHERE[/code], [code]ORDER BY[/code] and [code]GROUP BY[/code] statements.
1) CASE
We can say this is just like the switch case in programming languages.
Sample Queries:
[cc lang=”mysql”]
// Below will return zero
SELECT CASE 0 WHEN 0 THEN ‘zero’ WHEN 1 THEN ‘one’ ELSE ‘no one’ END;
// Below will return true
SELECT CASE WHEN 5>2 THEN ‘true’ ELSE ‘false’ END;
[/cc]
2) IF
This function takes the three parameters as expression, if expression one is true the it will return second parameter otherwise it will return third parameter.
Sample Queries:
[cc lang=”mysql”]
SELECT IF(expr1,expr2,expr3);
// return yes
SELECT IF(1<5,'yes','no');
[/cc]
3) IFNULL
This function takes two parameters as a expression. And if expression one is not num then it will return expression one otherwise it will return expression two.
Sample Queries:
[cc lang=”mysql”]
SELECT IFNULL(expr1, expr2);
// Return 5
SELECT IFNULL(5,0);
// Return 10
SELECT IFNULL(NULL,10);
[/cc]
4) NULLIF
This function takes two parameter as a expression. It will return [code]NULL[/code] if expr1=expr2 will return [code]TRUE[/code] otherwise it will return expr1.
Sample Queries:
[cc lang=”mysql”]
SELECT NULLIF(expr1,expr2);
// Return NULL
SELECT NULLIF(5,5);
// Return 10
SELECT NULLIF(10,4);
[/cc]
Note: MySQL evaluates expr1 twice if the arguments are not equal.