💻 Introduction
The CASE statement in SQL lets you add conditional logic inside your queries. It works like an IF-THEN-ELSE statement and returns values based on conditions.
—
1️⃣ Simple CASE Expression
Matches a column against specific values.
SELECT EmpID, FirstName,
CASE Department
WHEN 'HR' THEN 'Human Resources'
WHEN 'IT' THEN 'Technology'
WHEN 'FIN' THEN 'Finance'
ELSE 'Other'
END AS Department_Name
FROM Employees;
—
2️⃣ Searched CASE Expression
Uses logical conditions instead of direct matching.
SELECT EmpID, Salary,
CASE
WHEN Salary > 100000 THEN 'High'
WHEN Salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'Low'
END AS Salary_Level
FROM Employees;
—
3️⃣ CASE in ORDER BY
You can use CASE to control sorting order dynamically.
SELECT EmpID, FirstName, Department
FROM Employees
ORDER BY
CASE Department
WHEN 'HR' THEN 1
WHEN 'IT' THEN 2
ELSE 3
END;
—
✅ Key Takeaways
- Simple CASE → Compare a column to specific values.
- Searched CASE → Use conditions like >, <, BETWEEN.
- CASE can be used in SELECT, ORDER BY, GROUP BY.
- Acts like
IF-ELSEin SQL queries.
💡 CASE stops checking once a condition matches. Always put most restrictive conditions first.
—
📚 Continue Learning
💬 How are you using CASE in your SQL queries? Share in the comments!