The CASE Expression

The CASE expression is a more generic form of NULLIF() and COALESCE(). A CASE expression lets you map any given value into some other value. You can write a CASE expression in two different forms. The first form (called the simple form) looks like this:

CASE expression1
    WHEN value1 THEN result1
    WHEN value2 THEN result2
    ...
    [ ELSE resultn ]
END

When PostgreSQL evaluates a simple CASE expression, it computes the value of expression1 then compares the result to value1. If expression1 equals value1, the CASE expression evaluates to result1. If not, PostgreSQL compares expression1 to value1; if they match, the CASE expression evaluates to result2. PostgreSQL continues searching through the WHEN clauses until it finds a match. ...

Get PostgreSQL, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.