15. CASE: a value chosen by conditions

If it's like this, give this; if it's like that, give that. In SELECT, in ORDER BY and inside aggregates.

CASE WHEN: if... then...

Often we want a value that depends on a condition: products put into price bands, cheap, medium and expensive, say. CASE does it in one statement:

SELECT name, price,
       CASE
         WHEN price < 30  THEN 'cheap'
         WHEN price < 100 THEN 'medium'
         ELSE 'expensive'
       END AS price_band
FROM product
ORDER BY price, id;
namepriceprice_band
Pen15.0cheap
Potato Chips25.0cheap
Highlighter25.0cheap
Notebook30.0medium
Croissant35.0medium
Orange Juice40.0medium
Green Tea45.0medium
Coffee55.0medium
Banana Bread60.0medium
Dried Mango90.0medium
Cheesecake120.0expensive
Cashew Nuts150.0expensive
12 rows

The database reads the WHENs one at a time, top to bottom. The first one that is true gives the value after its THEN, and it stops there. When none is true, you get the value after ELSE. It always ends with END.

So the order of the WHENs matters. Pen, at 15 baht, fits both price < 30 and price < 100, but gets cheap, because the first one is true first.

Without ELSE, a row that fits no WHEN gets NULL:

SELECT name, stock,
       CASE
         WHEN stock = 0 THEN 'out of stock'
         WHEN stock < 20 THEN 'low'
       END AS warning
FROM product
ORDER BY stock, id;
namestockwarning
Orange Juice0out of stock
Highlighter0out of stock
Cheesecake8low
Banana Bread12low
Cashew Nuts20NULL
Croissant30NULL
Dried Mango45NULL
Notebook75NULL
Green Tea80NULL
Coffee120NULL
Potato Chips200NULL
Pen300NULL
12 rows

2 products are out of stock and 2 are low; the rest get NULL: nothing to warn about.

CASE x WHEN: comparing one value

When every condition compares the same column with different values, there is a short form: the column goes after CASE, and each WHEN takes just a value:

SELECT id, status,
       CASE status
         WHEN 'paid'      THEN 'pack it'
         WHEN 'shipped'   THEN 'done'
         WHEN 'cancelled' THEN 'refund?'
       END AS todo
FROM orders
WHERE id <= 6;
idstatustodo
1paidpack it
2shippeddone
3shippeddone
4paidpack it
5cancelledrefund?
6shippeddone
6 rows

CASE status WHEN 'paid' is CASE WHEN status = 'paid'. The short form only compares with "equals"; for <, LIKE, IS NULL or several columns, use the full form.

CASE phone WHEN NULL THEN ... is never true: the short form compares with =, and NULL = NULL is NULL, not true (chapter 5). To test for NULL, use the full form: CASE WHEN phone IS NULL THEN ....

CASE in ORDER BY: an order of your own

Statuses in alphabetical order come out cancelled, paid, shipped, which isn't the order of the work. The shop wants the orders to pack (paid) first, then the shipped ones, and the cancelled ones last. Turn each status into a number with CASE, and sort by that number:

SELECT id, ordered, status
FROM orders
ORDER BY CASE status
           WHEN 'paid'    THEN 1
           WHEN 'shipped' THEN 2
           ELSE 3
         END,
         ordered;
idorderedstatus
12026-09-02paid
42026-09-20paid
72026-10-10paid
92026-10-22paid
102026-10-28paid
122026-11-05paid
132026-11-11paid
152026-11-25paid
22026-09-05shipped
32026-09-12shipped
62026-10-03shipped
82026-10-15shipped
112026-11-02shipped
52026-10-01cancelled
142026-11-18cancelled
15 rows

The 8 paid orders come first (by date within the group), then the 5 shipped, and the 2 cancelled last. The number itself needn't be in the result.

CASE inside aggregates: counting by condition in one row

Chapter 10 counted the orders of each status with GROUP BY status, one row per status. To see every status as a column in one row, put CASE inside an aggregate:

SELECT count(*) AS all_orders,
       sum(CASE WHEN status = 'paid'      THEN 1 ELSE 0 END) AS paid,
       sum(CASE WHEN status = 'shipped'   THEN 1 ELSE 0 END) AS shipped,
       sum(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;
all_orderspaidshippedcancelled
15852
1 row

Each row gives 1 when its status matches and 0 when it doesn't, so the sum is the number of matching rows: 15 orders, split into 8, 5 and 2.

With GROUP BY it makes a cross table. For each month, the number of orders by status, and the sales of orders not cancelled:

SELECT strftime('%Y-%m', o.ordered) AS month,
       count(DISTINCT CASE WHEN o.status = 'paid'    THEN o.id END) AS paid,
       count(DISTINCT CASE WHEN o.status = 'shipped' THEN o.id END) AS shipped,
       sum(CASE WHEN o.status <> 'cancelled' THEN i.qty * i.price ELSE 0 END) AS sales
FROM orders o
JOIN order_item i ON i.order_id = o.id
GROUP BY month;
monthpaidshippedsales
2026-0922820.0
2026-10321450.0
2026-1131940.0
3 rows

A CASE without ELSE gives NULL for rows that don't match, and count skips NULL, so it counts only the orders of that status (DISTINCT because one order has several lines). The sales match chapter 10's: 820, 1,450 and 940 baht.

In SQLite and Phai SQL a condition is worth 1 (true) or 0 (false), so sum(status = 'paid') gives the same as sum(CASE WHEN status = 'paid' THEN 1 ELSE 0 END). The CASE form works in every database, though.

coalesce, nullif and iif

These three are short CASEs used so often that they have names of their own.

coalesce(a, b, ...) gives the first value that isn't NULL. Use it to put something readable where there is nothing:

SELECT name, coalesce(phone, '(no phone)') AS phone
FROM customer
WHERE city IN ('Bangkok', 'Phuket');
namephone
Somchai Jaidee081-234-5678
Anan Wongsa(no phone)
Pim Chaiya086-555-0101
Wichai Saelim083-999-0000
Siriporn Kaewdee(no phone)
Lalita Meesuk087-654-3210
6 rows

Anan Wongsa and Siriporn Kaewdee have no number, so they get (no phone) instead of NULL. It is the same as CASE WHEN phone IS NOT NULL THEN phone ELSE '(no phone)' END.

nullif(a, b) is the other way round: NULL when a equals b, otherwise a. Its most common use is avoiding division by zero. How many times its stock left has each product sold? The products out of stock have a stock of 0:

SELECT p.name, p.stock,
       coalesce(sum(i.qty), 0) AS sold,
       round(1.0 * coalesce(sum(i.qty), 0) / nullif(p.stock, 0), 2) AS sold_per_stock
FROM product p
LEFT JOIN order_item i ON i.product_id = p.id
GROUP BY p.id, p.name, p.stock
ORDER BY p.id;
namestocksoldsold_per_stock
Coffee12070.06
Green Tea8050.06
Orange Juice02NULL
Croissant3060.2
Banana Bread1230.25
Cheesecake830.38
Potato Chips200110.06
Dried Mango4540.09
Cashew Nuts2020.1
Notebook75180.24
Pen300350.12
Highlighter00NULL
12 rows

nullif(p.stock, 0) turns 0 into NULL, and dividing by NULL gives NULL instead of breaking: Orange Juice and Highlighter get NULL ("can't be worked out"). coalesce(sum(i.qty), 0) gives Highlighter, never sold, a 0 instead of NULL (as chapter 9 said), and 1.0 * makes the division give decimals.

SQLite and Phai SQL already give NULL for a division by zero, with no error, but many other databases stop with a "division by zero" error. Make nullif a habit: the statement works everywhere, and the reader sees that zero was thought of.

iif(condition, value if true, value if not) is a CASE WHEN ... THEN ... ELSE ... END with one condition, written shorter:

SELECT name, stock, iif(stock > 0, 'in stock', 'sold out') AS shelf
FROM product
WHERE category_id = 1;
namestockshelf
Coffee120in stock
Green Tea80in stock
Orange Juice0sold out
3 rows

iif is in SQLite (since 3.32) and Phai SQL, and SQL Server has one of the same name; some other databases haven't. For SQL that has to move, use CASE.

  1. Show every customer's name with 'has phone' or 'no phone' (with CASE or iif).
  2. For each customer (customer_id), how many orders are paid and how many cancelled, in one row.
  3. Show every product, the ones out of stock (stock = 0) first, the rest by name.
Show the answer
SELECT name, iif(phone IS NULL, 'no phone', 'has phone') AS phone FROM customer;
SELECT customer_id, sum(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid, sum(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled FROM orders GROUP BY customer_id;
SELECT name, stock FROM product ORDER BY CASE WHEN stock = 0 THEN 0 ELSE 1 END, name;
namephone
Somchai Jaideehas phone
Malee Srisukhas phone
Anan Wongsano phone
Pim Chaiyahas phone
Narin Thongdeehas phone
Kanya Boonmeehas phone
Wichai Saelimhas phone
Siriporn Kaewdeeno phone
Tawan Rungruanghas phone
Lalita Meesukhas phone
10 rows
customer_idpaidcancelled
120
210
311
411
500
610
720
800
8 rows
namestock
Highlighter0
Orange Juice0
Banana Bread12
Cashew Nuts20
Cheesecake8
Coffee120
Croissant30
Dried Mango45
Green Tea80
Notebook75
Pen300
Potato Chips200
12 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made