MySQL :: MySQL 8.0 Reference Manual :: 14.5 Flow Control Functions (original) (raw)

Table 14.7 Flow Control Operators

Name Description
CASE Case operator
IF() If/else construct
IFNULL() Null if/else construct
NULLIF() Return NULL if expr1 = expr2
mysql> SELECT CASE 1 WHEN 1 THEN 'one'  
    ->     WHEN 2 THEN 'two' ELSE 'more' END;  
        -> 'one'  
mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;  
        -> 'true'  
mysql> SELECT CASE BINARY 'B'  
    ->     WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;  
        -> NULL  
mysql> SELECT IF(1>2,2,3);  
        -> 3  
mysql> SELECT IF(1<2,'yes','no');  
        -> 'yes'  
mysql> SELECT IF(STRCMP('test','test1'),'no','yes');  
        -> 'no'  
mysql> SELECT IFNULL(1,0);  
        -> 1  
mysql> SELECT IFNULL(NULL,10);  
        -> 10  
mysql> SELECT IFNULL(1/0,10);  
        -> 10  
mysql> SELECT IFNULL(1/0,'yes');  
        -> 'yes'  

The default return type ofIFNULL(expr1,expr2) is the more “general” of the two expressions, in the order STRING, REAL, or INTEGER. Consider the case of a table based on expressions or where MySQL must internally store a value returned by IFNULL() in a temporary table:

mysql> CREATE TABLE tmp SELECT IFNULL(1,'test') AS test;  
mysql> DESCRIBE tmp;  
+-------+--------------+------+-----+---------+-------+  
| Field | Type         | Null | Key | Default | Extra |  
+-------+--------------+------+-----+---------+-------+  
| test  | varbinary(4) | NO   |     |         |       |  
+-------+--------------+------+-----+---------+-------+  

In this example, the type of the test column is VARBINARY(4) (a string type).

mysql> SELECT NULLIF(1,1);  
        -> NULL  
mysql> SELECT NULLIF(1,2);  
        -> 1  

Note
MySQL evaluates expr1 twice if the arguments are not equal.

The handling of system variable values by these functions changed in MySQL 8.0.22. For each of these functions, if the first argument contains only characters present in the character set and collation used by the second argument (and it is constant), the latter character set and collation is used to make the comparison. In MySQL 8.0.22 and later, system variable values are handled as column values of the same character and collation. Some queries using these functions with system variables that were previously successful may subsequently be rejected with Illegal mix of collations. In such cases, you should cast the system variable to the correct character set and collation.