🔹 What is a CASE Statement?
A CASE statement lets you apply conditional logic in SQL queries — kind of like an if-else in programming languages.
Basic Syntax:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE resultN
END
WHEN→ specifies the condition to checkTHEN→ the value returned if the condition is trueELSE→ optional, value returned if none of the conditions are trueEND→ closes the CASE
🔹 Example 1: Simple CASE with Conditions
Suppose we have a table Employees:
| EmployeeID | Name | Salary |
|---|---|---|
| 1 | Alice | 3000 |
| 2 | Bob | 6000 |
| 3 | Carol | 12000 |
| 4 | Dave | 8000 |
We want to categorize employees based on their salary.
SELECT
Name,
Salary,
CASE
WHEN Salary < 5000 THEN 'Low'
WHEN Salary BETWEEN 5000 AND 10000 THEN 'Medium'
ELSE 'High'
END AS SalaryCategory
FROM Employees;
Result:
| Name | Salary | SalaryCategory |
|---|---|---|
| Alice | 3000 | Low |
| Bob | 6000 | Medium |
| Carol | 12000 | High |
| Dave | 8000 | Medium |
🔹 Example 2: CASE in ORDER BY
We can sort results using custom rules:
SELECT Name, Salary
FROM Employees
ORDER BY
CASE
WHEN Salary < 5000 THEN 1
WHEN Salary BETWEEN 5000 AND 10000 THEN 2
ELSE 3
END;
This will order employees by salary category (Low → Medium → High).
🔹 Example 3: CASE in Aggregation
Count employees in each category:
SELECT
CASE
WHEN Salary < 5000 THEN 'Low'
WHEN Salary BETWEEN 5000 AND 10000 THEN 'Medium'
ELSE 'High'
END AS SalaryCategory,
COUNT(*) AS NumEmployees
FROM Employees
GROUP BY
CASE
WHEN Salary < 5000 THEN 'Low'
WHEN Salary BETWEEN 5000 AND 10000 THEN 'Medium'
ELSE 'High'
END;
✅ Key Points:
- CASE can be used in
SELECT,ORDER BY,WHERE, andGROUP BY. - Think of it as SQL’s if-else tool.
