Function Reference

CASE

SQL construct

Checks the WHEN branches in order and returns the result of the first matching one.

PostgreSQL 17.5
CASE [expression] WHEN condition THEN result [WHEN ...] [ELSE result] END

Parameters

expressionoptional
Expression compared with the values in the WHEN branches
conditionboolean
Condition of the branch, or the value to compare with expression if it is given
result
Value the branch returns when its condition is true
ELSE resultoptional
Value returned when no branch matches

Return value

The result of the first matching branch; NULL if no branch matches and there is no ELSE

Examples

Comparing two numbers

PostgreSQL 17.5
SELECT CASE
		WHEN 10 > 5 THEN 'greater'
		ELSE 'less or equal'
	END AS result;
result
greater

Family role by status

PostgreSQL 17.5
SELECT member_name,
	CASE
		WHEN status IN ('father', 'mother') THEN 'parent'
		ELSE 'child'
	END AS role
FROM FamilyMembers;
member_namerole
Headley Quinceyparent
Flavia Quinceyparent
Andie Quinceychild
Lela Quinceychild
Annie Quinceychild
Ernest Forrestparent
Constance Forrestparent
Wednesday Addamschild

Simple form without ELSE

PostgreSQL 17.5
SELECT member_name,
	CASE
		status
		WHEN 'father' THEN 'dad'
		WHEN 'mother' THEN 'mom'
	END AS parent_role
FROM FamilyMembers;
member_nameparent_role
Headley Quinceydad
Flavia Quinceymom
Andie Quincey<NULL>
Lela Quincey<NULL>
Annie Quincey<NULL>
Ernest Forrestdad
Constance Forrestmom
Wednesday Addams<NULL>

Details

CASE has two forms. Without expression, each WHEN has its own condition. With expression, it is compared with the value of each branch using =, so a WHEN NULL branch never matches: to check for NULL, use the form without expression and the condition WHEN expression IS NULL.

See also

Where to learn