SQL reference (MySQL and MariaDB dialects)

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#

FunctionWhat it doesDialect
CASEReturns 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
COALESCEReturns the first argument that is not NULL, or NULL if all are.MySQL and MariaDB
IFReturns expr2 if expr1 is true (not 0 and not NULL), expr3 otherwise.MySQL and MariaDB
IFNULLReturns expr1 if it is not NULL, expr2 otherwise.MySQL and MariaDB
ISNULLReturns 1 if expr is NULL, 0 otherwise.MySQL and MariaDB
NULLIFReturns NULL if expr1 = expr2 is true, expr1 otherwise.MySQL and MariaDB

CASE#

SQL
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] END

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. CASE is an expression, not the CASE statement of stored programs.

Example:

SQL
SELECT CASE 2 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END;

Result: two

COALESCE#

SQL
COALESCE(value, ...)

Returns the first argument that is not NULL, or NULL if all are.

Example:

SQL
SELECT COALESCE(NULL, NULL, 3);

Result: 3

IF#

SQL
IF(expr1, expr2, expr3)

Returns expr2 if expr1 is true (not 0 and not NULL), expr3 otherwise.

Example:

SQL
SELECT IF(1 > 2, 'a', 'b');

Result: b

IFNULL#

SQL
IFNULL(expr1, expr2)

Returns expr1 if it is not NULL, expr2 otherwise.

Example:

SQL
SELECT IFNULL(NULL, 'x');

Result: x

ISNULL#

SQL
ISNULL(expr)

Returns 1 if expr is NULL, 0 otherwise.

Example:

SQL
SELECT ISNULL(NULL), ISNULL(0);

Result: 1, 0

NULLIF#

SQL
NULLIF(expr1, expr2)

Returns NULL if expr1 = expr2 is true, expr1 otherwise.

Example:

SQL
SELECT NULLIF(1, 1), NULLIF(1, 2);

Result: NULL, 1

See also#