SQL CASE Expression
Here is a clear, practical, and complete guide to the SQL CASE expression, one of the most powerful tools for conditional logic inside SQL queries.
✅ What the CASE Expression Does
CASE lets you apply IF / ELSE style logic inside SQL.
It returns a value based on conditions and is often used in:
-
SELECT lists
-
ORDER BY
-
GROUP BY
-
UPDATE statements
-
Aggregations
🔹 Basic Syntax (Simple CASE)
Compares one expression to different values:
🔹 Searched CASE (most common)
Checks Boolean conditions:
📌 Practical Examples
1. Categorize numeric values
2. Replace NULL values
(Similar to COALESCE, but more flexible.)
3. Conditional aggregation
Count only active users:
4. Use CASE in ORDER BY
Sort VIP users first:
5. Conditional UPDATE
6. Dynamic grouping / bucketing
🧠 Important Notes
✔ CASE returns the first matching condition, then stops
✔ All results must be compatible data types
✔ ELSE is optional — default is NULL
✔ Works the same in PostgreSQL, MySQL, SQL Server, Oracle
🏎 Performance Tips
✔ Keep CASE expressions simple for readability
✔ Put most-likely conditions first for performance
✔ Use indexes on columns inside CASE conditions when possible
✔ For complex logic, consider creating computed columns or views
