TExcelTAD
Home › SQL › SQL CASE

SQL CASE

CASE is SQL's if/then/else. It goes through a list of conditions and returns the value of the first one that is true. If none is true, it returns the ELSE value — or NULL if there is no ELSE.

sql
CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ELSE default_result
END

CASE is an expression, so it can appear anywhere a value can: in SELECT, WHERE, ORDER BY, GROUP BY, inside aggregates, and in UPDATE … SET.

Price bands

sql · try it yourself
SELECT name, price,
       CASE
         WHEN price < 5  THEN 'budget'
         WHEN price < 30 THEN 'standard'
         ELSE 'premium'
       END AS price_band
FROM products
WHERE category_id IN (2, 6)
ORDER BY price;
name                        | price | price_band
----------------------------+-------+-----------
Bagels                      | 4.9   | budget
Sourdough Loaf              | 5.5   | standard
Butter Croissant            | 6.25  | standard
USB-C Cable                 | 9.99  | standard
Chocolate Cake              | 22    | standard
Wireless Mouse              | 24.99 | standard
Power Bank                  | 29.5  | standard
Mechanical Keyboard         | 89    | premium
Noise-Cancelling Headphones | 149   | premium
(9 rows)

The conditions are checked in order: a price of 4.9 matches price < 5 and never reaches the second WHEN.

Simple CASE

When every condition compares the same expression with a value, the short "simple" form is neater:

sql · try it yourself
SELECT order_id,
       status,
       CASE status
         WHEN 'delivered'  THEN 'Done'
         WHEN 'shipped'    THEN 'On the way'
         WHEN 'processing' THEN 'Being packed'
         ELSE 'Cancelled'
       END AS customer_message
FROM orders
WHERE order_id BETWEEN 33 AND 37
ORDER BY order_id;
order_id | status     | customer_message
---------+------------+-----------------
33       | delivered  | Done
34       | cancelled  | Cancelled
35       | processing | Being packed
36       | processing | Being packed
37       | processing | Being packed
(5 rows)

Grouping by a CASE

Count products per price band:

sql · try it yourself
SELECT CASE
         WHEN price < 5  THEN '1: under 5'
         WHEN price < 30 THEN '2: 5 to 30'
         ELSE '3: 30 and more'
       END AS band,
       COUNT(*) AS products
FROM products
GROUP BY band
ORDER BY band;
band           | products
---------------+---------
1: under 5     | 11
2: 5 to 30     | 12
3: 30 and more | 7
(3 rows)

Conditional aggregation

Put CASE inside an aggregate to count or sum only some rows — and build a pivot-style table in one pass. Orders per employee, split by status:

sql · try it yourself
SELECT employee_id,
       COUNT(*) AS total,
       SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
       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
GROUP BY employee_id
ORDER BY employee_id;
employee_id | total | delivered | shipped | cancelled
------------+-------+-----------+---------+----------
4           | 11    | 3         | 4       | 2
5           | 6     | 3         | 1       | 2
6           | 16    | 7         | 4       | 2
9           | 7     | 3         | 0       | 1
(4 rows)

Custom sort order

Sort statuses in business order rather than alphabetically:

sql · try it yourself
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY CASE status
           WHEN 'processing' THEN 1
           WHEN 'shipped'    THEN 2
           WHEN 'delivered'  THEN 3
           ELSE 4
         END;
status     | orders
-----------+-------
processing | 8
shipped    | 9
delivered  | 16
cancelled  | 7
(4 rows)

CASE in UPDATE

Different raises for different titles in one statement:

sql · try it yourself
UPDATE employees
SET salary = salary + CASE
                        WHEN title = 'Sales Rep' THEN 3000
                        WHEN title LIKE '%Manager' THEN 5000
                        ELSE 0
                      END;

SELECT first_name, title, salary FROM employees WHERE employee_id <= 5 ORDER BY employee_id;
10 rows affected.

first_name | title              | salary
-----------+--------------------+-------
Grace      | CEO                | 185000
Victor     | Sales Manager      | 103000
Lin        | Operations Manager | 100000
Rosa       | Sales Rep          | 65000
Tom        | Sales Rep          | 61000
(5 rows)

Tip: Many databases also have shortcuts: IIF(cond, a, b) (SQLite 3.32+, SQL Server) and IF(cond, a, b) (MySQL). CASE works everywhere.

Test yourself

What does CASE return when no WHEN matches and there is no ELSE?

  1. 0
  2. An empty string
  3. NULL
  4. An error

With WHEN price < 30 THEN 'a' WHEN price < 5 THEN 'b', what does a price of 3 get?

  1. 'a'
  2. 'b'
  3. both
  4. NULL