CASE WHEN in MySQL — How It Works
What the MySQL CASE WHEN function does, with an example.
Published October 22, 2026
CASE WHEN evaluates conditions in order and returns the result of the first that is true, with an optional ELSE. It brings if/else logic into SQL.
How it works
It works in SELECT, WHERE, ORDER BY and aggregates.
Try it in MySQL
SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END
grade
SELECT SUM(CASE WHEN status='paid' THEN 1 ELSE 0 END) FROM orders
paid count
SELECT * FROM t ORDER BY CASE WHEN pinned THEN 0 ELSE 1 END, id
pinned first
Practical examples
Example 1
SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END;
-- gradeExample 2
SELECT SUM(CASE WHEN status='paid' THEN 1 ELSE 0 END) FROM orders;
-- paid countExample 3
SELECT * FROM t ORDER BY CASE WHEN pinned THEN 0 ELSE 1 END, id;
-- pinned firstUse it in a real query
SELECT id, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS result
FROM your_table
LIMIT 10;Common mistakes
- Forgetting END or ELSE (NULL result).
- Ordering conditions wrongly.
- Overlapping ranges.
Key takeaways
- CASE WHEN in one line: CASE WHEN evaluates conditions in order and returns the result of the first that is true, with an optional ELSE.
- Try queries in a test database first.
- Check NULL handling and data types.
FAQ
Simple vs searched CASE?
Simple compares one expression; searched evaluates boolean conditions.
Does CASE WHEN work in other databases?
Most have an equivalent, but names and syntax vary between MySQL, PostgreSQL, SQL Server and SQLite.