CASE WHEN
CASE WHEN adds if/else logic inside a query.
In this page:
Syntax
SELECT CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END
FROM table_name;
CASE WHEN
CASE WHEN condition THEN result ... ELSE default END evaluates conditions in order and returns the first matching result. It can appear in SELECT, WHERE, ORDER BY and inside aggregates.
The simple form CASE column WHEN value THEN ... compares one column against values.
Note:
Add an ELSE branch, otherwise unmatched rows return NULL.
Example: CASE WHEN
CREATE TABLE marks (id INTEGER PRIMARY KEY, name TEXT, score INTEGER);
INSERT INTO marks VALUES (1, 'Ada', 92), (2, 'Bob', 74), (3, 'Cy', 55), (4, 'Di', 38);
SELECT name, score,
CASE WHEN score >= 90 THEN 'A' WHEN score >= 70 THEN 'B' WHEN score >= 50 THEN 'C' ELSE 'F' END AS grade
FROM marks ORDER BY id;
SELECT SUM(CASE WHEN score >= 50 THEN 1 ELSE 0 END) AS passed FROM marks;
-- Output:
-- name | score | grade
-- Ada | 92 | A
-- Bob | 74 | B
-- Cy | 55 | C
-- Di | 38 | F
-- passed
-- 3
Login to try C/C++/Java/PHP code in the editor
Related Topics
Common Mistakes
- Forgetting END
- Omitting ELSE and getting NULL
- Overlapping conditions in the wrong order
Chapter Summary
- CASE WHEN ... THEN ... ELSE ... END
- Conditions are checked in order
- No ELSE returns NULL
- Usable in SELECT, ORDER BY and aggregates
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: