CASE expressions
Overview
So far each column has been a straight value or a calculation. Often you need a decision: if the price is over 50, call it premium; if the order is paid, it needs packing; if the phone is missing, show the email. SQL’s tool for this is the CASE expression — an if/else that you can use anywhere a value is allowed.
The searched CASE
The most flexible form lists conditions one after another:
SELECT name, price,
CASE
WHEN price >= 50 THEN 'premium'
WHEN price >= 15 THEN 'standard'
ELSE 'budget'
END AS price_band
FROM products
ORDER BY price DESC; name | price | price_band
------------------------+-------+------------
Burr Grinder | 89.00 | premium
Electric Kettle | 59.90 | premium
Glass Teapot | 32.00 | standard
Gift Card | 25.00 | standard
Pour-Over Dripper | 24.00 | standard
Darjeeling First Flush | 18.00 | standard
Ethiopian Yirgacheffe | 14.50 | budget
Jasmine Green | 12.75 | budget
Colombian Supremo | 12.00 | budget
Decaf House Blend | 11.25 | budget
Assam Breakfast | 9.50 | budget
Chamomile Calm | 8.00 | budget
(12 rows)How it works:
- Each
WHENcondition is tested in order. - The first one that is true decides the result, and the rest are skipped.
- If none is true, the
ELSEvalue is used. ENDcloses the expression, andASnames the column as usual.
Because the first true condition wins, order matters. The Burr Grinder’s price of 89 is also >= 15, but it never reaches that test. Put the conditions the other way round and everything over 15 becomes “standard”:
SELECT name, price,
CASE
WHEN price >= 15 THEN 'standard'
WHEN price >= 50 THEN 'premium' -- never reached
ELSE 'budget'
END AS price_band
FROM products
WHERE price > 50; name | price | price_band
-----------------+-------+------------
Burr Grinder | 89.00 | standard
Electric Kettle | 59.90 | standard
(2 rows)What happens without ELSE
ELSE is optional. If you leave it out and no condition matches, the result is NULL:
SELECT name, stock,
CASE
WHEN stock = 0 THEN 'out of stock'
WHEN stock < 15 THEN 'low'
END AS warning
FROM products
WHERE category_id = 3; name | stock | warning
-------------------+-------+--------------
Pour-Over Dripper | 15 |
Burr Grinder | 6 | low
Electric Kettle | 10 | low
Glass Teapot | 0 | out of stock
(4 rows)That can be exactly what you want — only flag the problems — but if you mean “otherwise, something”, write the ELSE.
All the THEN and ELSE results must be of compatible types. Mixing text and numbers, such as THEN 'none' ELSE stock, is an error; cast with stock::text if you really want text.
The simple CASE
When every condition compares the same expression for equality, there’s a shorter form: put the expression after CASE and just the values after each WHEN:
SELECT id, status,
CASE status
WHEN 'pending' THEN 'Awaiting payment'
WHEN 'paid' THEN 'Paid'
WHEN 'shipped' THEN 'On its way'
WHEN 'delivered' THEN 'Delivered'
ELSE 'Cancelled'
END AS label
FROM orders
WHERE id >= 20; id | status | label
----+---------+------------------
20 | shipped | On its way
21 | paid | Paid
22 | paid | Paid
23 | pending | Awaiting payment
24 | pending | Awaiting payment
(5 rows)The simple form only tests equality, so it can’t express ranges, and WHEN NULL never matches (because NULL = NULL isn’t true). For anything beyond “equals one of these values”, use the searched form.
CASE and NULL
To treat missing values specially, test IS NULL in a searched CASE:
SELECT first_name,
CASE
WHEN phone IS NULL THEN 'email only'
WHEN phone LIKE '+91%' THEN 'call (India)'
ELSE 'call (international)'
END AS contact_method
FROM customers
ORDER BY id; first_name | contact_method
------------+----------------------
Asha | call (India)
Ben | call (international)
Chen | email only
Dee | call (international)
Elena | email only
Farhan | call (India)
Grace | call (international)
Hugo | email only
Isha | call (India)
Jack | email only
(10 rows)For the simple job of “use this value, or a default if it’s NULL”, COALESCE is shorter — it’s really just a compact CASE.
Custom sort orders
ORDER BY status sorts alphabetically: cancelled, delivered, paid, pending, shipped. That’s rarely the order a person wants. A CASE in ORDER BY maps each value to a number, and the rows sort by that number:
SELECT id, status, ordered_at::date AS day
FROM orders
WHERE ordered_at >= '2026-09-01'
ORDER BY CASE status
WHEN 'pending' THEN 1
WHEN 'paid' THEN 2
WHEN 'shipped' THEN 3
WHEN 'delivered' THEN 4
ELSE 5
END,
ordered_at; id | status | day
----+-----------+------------
23 | pending | 2026-11-20
24 | pending | 2026-11-29
21 | paid | 2026-10-27
22 | paid | 2026-11-08
18 | shipped | 2026-09-01
20 | shipped | 2026-10-03
19 | delivered | 2026-09-19
(7 rows)The orders now follow the lifecycle. The sort key doesn’t need to appear in the select list.
Bucketing numbers
CASE is the standard way to turn a continuous number into categories — stock levels, price bands, age groups, order sizes:
SELECT order_id,
sum(quantity * unit_price) AS items_total,
CASE
WHEN sum(quantity * unit_price) >= 100 THEN 'large'
WHEN sum(quantity * unit_price) >= 40 THEN 'medium'
ELSE 'small'
END AS size
FROM order_items
WHERE order_id <= 6
GROUP BY order_id
ORDER BY order_id; order_id | items_total | size
----------+-------------+--------
1 | 38.50 | small
2 | 113.00 | large
3 | 18.00 | small
4 | 62.25 | medium
5 | 59.90 | medium
6 | 55.50 | medium
(6 rows)This uses GROUP BY and sum, which you’ll learn properly in the next chapter: it adds up each order’s items into one total, and the CASE labels each total.
A preview: CASE inside aggregates
One of the most powerful uses of CASE is counting or summing only some rows. How many products are in stock, and how many aren’t — in a single query?
SELECT count(*) AS products,
sum(CASE WHEN stock > 0 THEN 1 ELSE 0 END) AS in_stock,
sum(CASE WHEN stock = 0 THEN 1 ELSE 0 END) AS out_of_stock
FROM products; products | in_stock | out_of_stock
----------+----------+--------------
12 | 10 | 2
(1 row)Each row contributes 1 or 0 to each sum, so each sum counts the rows matching its condition. This pattern — conditional aggregation — turns rows into columns for reports, and you’ll use it a lot. PostgreSQL also has a tidier spelling, count(*) FILTER (WHERE stock > 0), covered in Aggregate functions.
CASE in WHERE
CASE can appear in WHERE too, but there’s almost always a clearer way with AND and OR. If you find yourself writing WHERE CASE … END = 'x', try rewriting the condition directly — it’ll be easier to read and to index.
Tip: format CASE expressions with each
WHENon its own line, indented underCASE, and line up theTHENs. Long CASEs become readable tables of rules.
A to-do list for the warehouse
The warehouse wants every order that isn't delivered yet, with a plain-English action: 'Wait for payment' for pending orders, 'Pack and ship' for paid ones, 'Track parcel' for shipped ones, and 'No action' for anything else. Return id, status and action, sorted so that paid orders come first (they're the urgent ones), then pending, then shipped, then everything else — and by id within each group. Use a CASE expression in ORDER BY for the custom order.
SELECT id, status
FROM orders
WHERE status <> 'delivered'
ORDER BY id;SELECT id, status,
CASE status
WHEN 'pending' THEN 'Wait for payment'
WHEN 'paid' THEN 'Pack and ship'
WHEN 'shipped' THEN 'Track parcel'
ELSE 'No action'
END AS action
FROM orders
WHERE status <> 'delivered'
ORDER BY CASE status
WHEN 'paid' THEN 1
WHEN 'pending' THEN 2
WHEN 'shipped' THEN 3
ELSE 4
END,
id;Summary
- CASE WHEN condition THEN result … ELSE result END is SQL's if/else, and it can go anywhere a value can.
- Conditions are tested top to bottom and the first true one wins, so put the most specific conditions first.
- Without ELSE, rows that match no condition get NULL.
- The simple form CASE column WHEN value THEN … compares one expression with a list of values.
- CASE in ORDER BY gives custom sort orders; CASE inside aggregates (or the FILTER clause) counts and sums conditionally.