Control flow functions
CASE, IF, IFNULL, NULLIF, COALESCE and ISNULL: choosing a value by a condition or by NULL.
These functions choose between values. They are evaluated for every row; arguments that are not chosen may still be evaluated, so do not rely on them to avoid an error.
The type of the result is the merged type of the possible results (COALESCE, IFNULL, IF and CASE merge their results' types as MySQL does; see Type conversion). GREATEST and LEAST are on Numeric functions.
NVL, NVL2, DECODE (Oracle compatibility of MariaDB) are not supported yet.
Summary of functions#
| Function | What it does | Dialect |
|---|---|---|
CASE | Returns the result of the first WHEN whose value equals value (first form) or whose condition is true (second form); the ELSE result if there is none; NULL if there is no ELSE. | MySQL and MariaDB |
COALESCE | Returns the first argument that is not NULL, or NULL if all are. | MySQL and MariaDB |
IF | Returns expr2 if expr1 is true (not 0 and not NULL), expr3 otherwise. | MySQL and MariaDB |
IFNULL | Returns expr1 if it is not NULL, expr2 otherwise. | MySQL and MariaDB |
ISNULL | Returns 1 if expr is NULL, 0 otherwise. | MySQL and MariaDB |
NULLIF | Returns NULL if expr1 = expr2 is true, expr1 otherwise. | MySQL and MariaDB |
CASE#
CASE value WHEN compare_value THEN result [WHEN compare_value THEN result ...] [ELSE result] END
CASE WHEN condition THEN result [WHEN condition THEN result ...] [ELSE result] ENDReturns the result of the first WHEN whose value equals value (first form) or whose condition is true (second form); the ELSE result if there is none; NULL if there is no ELSE. CASE is an expression, not the CASE statement of stored programs.
Example:
SELECT CASE 2 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END;Result: two
COALESCE#
COALESCE(value, ...)Returns the first argument that is not NULL, or NULL if all are.
Example:
SELECT COALESCE(NULL, NULL, 3);Result: 3
IF#
IF(expr1, expr2, expr3)Returns expr2 if expr1 is true (not 0 and not NULL), expr3 otherwise.
Example:
SELECT IF(1 > 2, 'a', 'b');Result: b
IFNULL#
IFNULL(expr1, expr2)Returns expr1 if it is not NULL, expr2 otherwise.
Example:
SELECT IFNULL(NULL, 'x');Result: x
ISNULL#
ISNULL(expr)Returns 1 if expr is NULL, 0 otherwise.
Example:
SELECT ISNULL(NULL), ISNULL(0);Result: 1, 0
NULLIF#
NULLIF(expr1, expr2)Returns NULL if expr1 = expr2 is true, expr1 otherwise.
Example:
SELECT NULLIF(1, 1), NULLIF(1, 2);Result: NULL, 1