039 SQL CASE
The page explains the SQL CASE expression, which is used to add if-then-else logic within SQL queries.
- The
CASEexpression checks conditions one by one and returns a value for the first condition that is true, similar to an if-then-else statement in other programming languages. - If none of the conditions is true, the value after
ELSEis returned. If there is noELSEand no condition is true, it returns NULL. - Syntax:
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE result END; - Examples include:
- Returning a label based on the value of a column (e.g., if Quantity > 30, return 'The quantity is greater than 30').
- Using
CASEin anORDER BYclause to sort by one column unless it's NULL, in which case it sorts by another column.
The page also includes interactive examples and a quiz question to reinforce understanding.[1]
SQL CASE Expression
The SQL CASE Expression
The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.
CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
| OrderDetailID | OrderID | ProductID | Quantity |
|---|---|---|---|
| 1 | 10248 | 11 | 12 |
| 2 | 10248 | 42 | 10 |
| 3 | 10248 | 72 | 5 |
| 4 | 10249 | 14 | 9 |
| 5 | 10249 | 51 | 40 |
SQL CASE Examples
The following SQL goes through conditions and returns 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 under 30'
END AS QuantityText
FROM OrderDetails;
The following SQL will order the customers by City. However, if City is NULL, then order by Country:
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);