PostgreSQL CASE
CASE is SQL's if/else. It evaluates conditions in order and returns the value of the first one that is true. You can use it anywhere an expression is allowed: in the select list, WHERE, ORDER BY, GROUP BY, inside aggregates and in UPDATE.
Searched CASE
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
ENDLabel every book by its price:
SELECT title, price,
CASE
WHEN price < 10 THEN 'budget'
WHEN price < 20 THEN 'standard'
WHEN price < 40 THEN 'premium'
ELSE 'collector'
END AS price_band
FROM books
WHERE category_id IN (4, 6)
ORDER BY price; title | price | price_band
---------------------------+-------+------------
Moon Socks | 7.50 | budget
Ten Tiny Dragons | 8.99 | budget
Algorithms on a Napkin | 35.00 | premium
Learning SQL the Calm Way | 39.90 | premium
Rust for Curious Minds | 42.50 | collector
Postgres in Practice | 44.00 | collector
(6 rows)
The conditions are checked top to bottom, and the first true one wins. A book at 15.00 is "standard", even though price < 40 is also true for it.
Simple CASE
When every branch compares the same expression with a value, the short form reads better:
SELECT id, status,
CASE status
WHEN 'pending' THEN 'Waiting for payment'
WHEN 'shipped' THEN 'On its way'
WHEN 'delivered' THEN 'Arrived'
ELSE 'Cancelled'
END AS message
FROM orders
WHERE id >= 16
ORDER BY id; id | status | message
----+-----------+---------------------
16 | shipped | On its way
17 | shipped | On its way
18 | pending | Waiting for payment
19 | pending | Waiting for payment
20 | cancelled | Cancelled
(5 rows)
No ELSE means NULL
If no condition matches and there is no ELSE, the result is NULL:
SELECT name, birth_year,
CASE WHEN birth_year < 1970 THEN 'born before 1970' END AS note
FROM authors
WHERE id IN (2, 3, 9); name | birth_year | note
----------------+------------+------------------
Lars Henriksen | 1962 | born before 1970
Aiko Tanaka | 1988 |
Jonas Weber | |
(3 rows)
CASE inside aggregates: pivoting
CASE inside sum or count turns rows into columns. Copies sold per category, split by half-year:
SELECT cat.name AS category,
sum(CASE WHEN o.order_date < '2024-07-01' THEN oi.quantity ELSE 0 END) AS h1,
sum(CASE WHEN o.order_date >= '2024-07-01' THEN oi.quantity ELSE 0 END) AS h2
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN books b ON b.id = oi.book_id
JOIN categories cat ON cat.id = b.category_id
GROUP BY cat.name
ORDER BY cat.name; category | h1 | h2
-----------------+----+----
Children | 6 | 6
Fiction | 4 | 3
History | 3 | 0
Mystery | 2 | 5
Programming | 7 | 2
Science Fiction | 4 | 4
(6 rows)
(The FILTER clause from the aggregates lesson is a PostgreSQL alternative: sum(oi.quantity) FILTER (WHERE …).)
CASE in ORDER BY and UPDATE
A custom sort order, and a conditional price change in a single UPDATE:
SELECT name, job_title
FROM employees
ORDER BY CASE WHEN manager_id IS NULL THEN 0
WHEN manager_id = 1 THEN 1
ELSE 2 END,
name;
UPDATE books
SET price = CASE WHEN stock = 0 THEN price * 0.5
WHEN stock > 20 THEN price * 0.9
ELSE price END
WHERE stock = 0 OR stock > 20;
SELECT title, stock, price FROM books WHERE stock = 0 OR stock > 20 ORDER BY id; name | job_title
----------------+---------------------
Rachel Adams | Managing Director
Nadia Hussein | Head of Online
Victor Chen | Store Manager
Lucy Evans | Bookseller
Omar Farouk | Web Developer
Paul Becker | Bookseller
Sara Lindqvist | Support Agent
Tim Novak | Warehouse Assistant
(8 rows)
UPDATE 4
title | stock | price
-------------------+-------+-------
Harbor Lights | 0 | 6.25
The Age of Canals | 0 | 12.48
Ten Tiny Dragons | 30 | 8.09
Moon Socks | 25 | 6.75
(4 rows)
Note: All branches of a
CASEmust return compatible types.CASE WHEN x THEN 1 ELSE 'none' ENDfails because'none'is not a number; writeELSE NULLor cast the number to text.
Test yourself
Several WHEN conditions are true. Which result does CASE return?
- The last true one
- The first true one
- All of them
- An error
What does a CASE without ELSE return when nothing matches?
- 0
- An empty string
- NULL
- An error
Which expression counts only delivered orders?
- count(status = 'delivered')
- sum(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END)
- count(*) WHERE delivered
- CASE count(*) WHEN 'delivered'