Evaluate the conditions sequentially and return a value as soon as the first condition is satisfied.
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 under 30” END FROM OrderDetails; |
The CASE statement evaluates conditions and returns a value when the first condition is satisfied, similar to an IF-THEN-ELSE statement. Once a condition is met, it stops evaluating further conditions and returns the corresponding result.
If none of the conditions are met, it returns the value specified in the ELSE clause.
If there is no ELSE clause and no conditions are met, it returns NULL.
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN conditionN THEN resultN ELSE result END; |
Parameter |
Description |
condition1, |
Required: The conditions, evaluated in the order they are listed. |
result1, result2, …resultN |
Required: The value to return when a condition evaluates to true. |
Works in: |
From MySQL version 4.0 |
The following SQL statement will sort customers by their city. If the city is NULL for any customer, it will then sort by the country instead.
SELECT CustomerName, City, Country FROM Customers ORDER BY (CASE WHEN City IS NULL THEN Country ELSE City END); |