Loading lessons...
CASE Expression
The CASE expression is like an if-then-else in SQL. It checks conditions and returns a value for the first one that is true.
Basic example
sql
### SELECT OrderID, Quantity,
### CASE
### WHEN Quantity > 30 THEN 'big'
### WHEN Quantity > 20 THEN 'medium'
### ELSE 'small'
### END AS Size
### FROM OrderDetails;
How it works
- Conditions are checked top to bottom.
- The first TRUE condition wins.
- If none match,
ELSEis returned.
ENDfinishes the CASE;AS Sizenames the column.
ELSE is optional
If there is no ELSE and nothing matches, the result is NULL.
CASE in WHERE
sql
### SELECT CustomerName, City
### FROM Customers
### ORDER BY
(CASE
### WHEN City IS NULL THEN 1
### ELSE 0
### END), City;
Sorts NULL cities last.
CASE in ORDER BY
CASE is also handy for custom sorting, like always keeping a certain product on top.
TL;DR
- CASE is if-then-else for SQL.
- First true WHEN wins.
- ELSE is the fallback (NULL if missing).
- Usable in SELECT, WHERE, and ORDER BY.