conditional

CASE WHEN

SQL's portable if/else-if expression. Evaluates each WHEN clause in order and returns the first matching result; returns NULL from an unmatched CASE without ELSE.

CASE WHEN cond1 THEN result1 [WHEN ...] [ELSE default] END

Parameters / Modifiers

Parameter Purpose
Searched CASE CASE WHEN cond THEN ... — each condition is a boolean expression
Simple CASE CASE expr WHEN value THEN ... — compares expr to each value
ELSE Default result when no WHEN matches (defaults to NULL if omitted)
FILTER (WHERE ...) Postgres shorthand replacing CASE inside aggregates

Examples

SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 75 THEN 'B' ELSE 'C' END FROM tests;

Letter grade per row

SELECT SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) FROM invoices;

Conditional sum without a WHERE clause

SELECT CASE country WHEN 'US' THEN 'North America' WHEN 'IN' THEN 'Asia' ELSE 'Other' END FROM users;

Simple CASE form

SELECT COUNT(*) FILTER (WHERE status = 'paid') FROM invoices;

Postgres shorthand for the same conditional aggregation as example 2

Dialect notes / Gotcha

Every branch must produce a compatible type — mixing text and int raises an error. Order of WHEN clauses matters; the first true one wins.

Related functions

← All SQL functions · SQL cheat sheet · Window functions · PostgreSQL cheat sheet