SQL CASE WHEN

CASE is SQL's if/else. It checks conditions in order and returns the value of the first one that is true, or the ELSE value if none are.

Inside aggregates, CASE turns rows into columns: SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) counts delivered orders. This is called conditional aggregation.

Syntax

CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ELSE result3
END

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

case-when.sql · PostgreSQL
Loading editor…

Examples

1. Bucket values

SELECT name, price, CASE WHEN price < 25 THEN 'budget' WHEN price <= 100 THEN 'mid' ELSE 'premium' END AS band FROM products;

Each product in a price band.

2. Conditional aggregation

SELECT SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered, SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled FROM orders;

Several counts in one row.

Common mistakes

  • Ordering conditions badly: the first true WHEN wins, so put specific conditions first.
  • Forgetting END.

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 20 pts

Return each product's name and a band: 'budget' if price is under 25, 'mid' if 25 to 100 (inclusive), otherwise 'premium'.

challenge.sql · PostgreSQL
Loading editor…

FAQ

What happens if no WHEN matches and there is no ELSE?

The result is NULL.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →