How to use CASE expressions in SQL
· Category: SQL & Databases
Short answer
CASE provides if-then-else logic within a query. It can be used as a simple switch or as a searched expression with boolean conditions.
Steps
- Simple CASE:
SELECT CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Good' ELSE 'Average' END FROM scores; - Searched CASE:
SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END FROM scores; - Use in aggregates:
SELECT SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) FROM orders; - Use in ORDER BY:
ORDER BY CASE WHEN priority = 'high' THEN 1 ELSE 2 END - Wrap in a column alias for readability.
Tips
- Always include an
ELSEclause to avoid unexpectedNULLresults. CASEshort-circuits: conditions are evaluated in order.
Common issues
- Mismatched data types across
THENbranches cause type conversion errors. - Using
CASEinsideWHEREis redundant; filter withWHEREdirectly when possible.r