MySQL CASE Function
THE WORLD'S LARGEST WEB DEVELOPER SITE

MySQL CASE Function

❮ MySQL Functions

Example

Evaluate conditions and return a value when the first condition is met:

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN "The quantity is greater than 30"
    WHEN Quantity = 30 THEN "The quantity is 30"
    ELSE "The quantity is something else"
END
FROM OrderDetails;
Try it Yourself »

Definition and Usage

The CASE function lets you evaluate conditions and return a value when the first condition is met (like an IF-THEN-ELSE statement).

Syntax

CASE expression
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
   ...
    WHEN conditionN THEN resultN
    ELSE result
END

Parameter Values

Parameter Description
expression Optional. The value to compare to the list of conditions
condition1, condition2, ...conditionN Required. Evaluated in the order they are listed. Once a condition is true, the CASE function will return the result and not evaluate the conditions any further
result1, result2, ...resultN Required. The value to return once a condition is true

Note:

  • If no condition is true, the CASE function will return the value in the ELSE clause
  • If the ELSE clause is omitted and no condition is true, the CASE function will return NULL

Technical Details

Works in: MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23

More Examples

Example

Evaluate conditions and return a value when the first condition is met:

SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END);
Try it Yourself »

❮ MySQL Functions