The CASE Expression
Add conditional logic to your SQL queries with the CASE expression.
💡 CASE Expression are essential tools for handling conditional logic and NULL values in SQL.
CASE Syntax
-- Simple CASE (exact match)
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
ELSE default_result
END
-- Searched CASE (conditions)
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END
Example
SELECT
first_name,
salary,
CASE
WHEN salary >= 80000 THEN 'High'
WHEN salary >= 60000 THEN 'Medium'
ELSE 'Low'
END AS salary_level,
''
FROM employees;
✅ Key Takeaways
- CASE adds if-then-else logic to SQL queries
- CASE can be used in SELECT, WHERE, ORDER BY, and UPDATE
- CASE has two forms: simple (exact match) and searched (conditions)
- Always include an ELSE clause in CASE to handle unexpected values
- CASE expressions can be nested for complex logic