This guide is specifically for MySQL syntax.
How to SQL CASE WHEN Statement Examples in SQL
Add conditional logic to queries using CASE WHEN THEN ELSE END.
Quick Answer
SELECT name, CASE WHEN salary > 50000 THEN 'High' ELSE 'Low' END as level FROM employees;
Explanation
CASE evaluates conditions in order and returns the result when a condition is true. ELSE handles unmatched cases. Always end with END.
Query Variants
Simple
SELECT name, CASE WHEN salary > 100000 THEN 'Executive' WHEN salary > 50000 THEN 'Senior' ELSE 'Junior' END as level FROM employees;
In Aggregate
SELECT department, SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) as male_count, SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) as female_count FROM employees GROUP BY department;
In Orderby
SELECT * FROM tasks ORDER BY CASE priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END;
Pro Tips
- Conditions are evaluated in order
- ELSE is optional but recommended
- Can be used in SELECT, WHERE, ORDER BY
Related SQL Queries
Continue learning with more SQL query examples:
MySQL-Specific Notes
This page covers MySQL syntax. Other databases may have different syntax for similar operations.