Careeroza
CASE
The SQL CASE Expression
CASE goes through conditions and returns a value when the first condition is met (like if-then-else). If no condition is true, it returns the ELSE value, or NULL if there is no ELSE.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result
ENDCategorize Values
Example
Sort products into price bands:
SELECT ProductName, Price,
CASE
WHEN Price >= 15 THEN 'Premium'
WHEN Price >= 8 THEN 'Standard'
ELSE 'Budget'
END AS PriceBand
FROM Products;Result: 6 rows
| ProductName | Price | PriceBand |
|---|---|---|
| Basmati Rice 5kg | 12.5 | Standard |
| Green Tea 100 bags | 6.75 | Budget |
| Olive Oil 1L | 9.99 | Standard |
| Dark Chocolate | 3.49 | Budget |
| Espresso Beans 1kg | 18 | Premium |
| Almonds 500g | 8.25 | Standard |
Simple CASE
Example
Compare one expression with several values:
SELECT FirstName, Department,
CASE Department
WHEN 'Sales' THEN 'Revenue'
WHEN 'Support' THEN 'Customer Care'
ELSE 'Back Office'
END AS Division
FROM Employees;Result: 6 rows
| FirstName | Department | Division |
|---|---|---|
| Rahul | Sales | Revenue |
| Sara | Sales | Revenue |
| David | Sales | Revenue |
| Ananya | Support | Customer Care |
| James | Support | Customer Care |
| Fatima | Finance | Back Office |
CASE in ORDER BY and Aggregates
Example
Count orders above and below 100 in one query (a "pivot"):
SELECT SUM(CASE WHEN Amount >= 100 THEN 1 ELSE 0 END) AS LargeOrders,
SUM(CASE WHEN Amount < 100 THEN 1 ELSE 0 END) AS SmallOrders
FROM Orders;Result: 1 row
| LargeOrders | SmallOrders |
|---|---|
| 5 | 3 |
Example (ORDER BY)
Custom sort: show India first, then the rest alphabetically:
SELECT CustomerName, Country FROM Customers
ORDER BY CASE WHEN Country = 'India' THEN 0 ELSE 1 END, Country;Result: 8 rows
| CustomerName | Country |
|---|---|
| Aarav Traders | India |
| Delta Mart | India |
| Cedar & Co | Canada |
| Fjord Supplies | Norway |
| Golden Spoon | Singapore |
| Blue Harbor Foods | UK |
| Harbor Lights | UK |
| Evergreen Grocers | USA |