← Back to PostgreSQL Course | Chapter 5: Filtering & Functions | Lesson 5 of 7

CASE WHEN

CASE WHEN adds if/else logic inside a query.

In this page:

  1. CASE WHEN
Syntax
sql
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

sql
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
Related Topics
Common Mistakes
  1. Forgetting END
  2. Omitting ELSE and getting NULL
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.