SQL CASE WHEN

CASE is SQL’s if-then-else. It checks conditions in order and returns the value for the first one that’s true. You can use it anywhere a value goes: in SELECT, ORDER BY, GROUP BY and inside aggregates.

Updated December 1, 2026

Syntax

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

Label rows into buckets

Conditions are checked top to bottom, so the second WHEN only sees drinks that cost $4 or more.

SELECT name, price,
       CASE
         WHEN price < 4 THEN 'budget'
         WHEN price < 5 THEN 'standard'
         ELSE 'premium'
       END AS price_band
FROM drinks
ORDER BY price;
Result on the SQL Café sample data (10 rows)
namepriceprice_band
Espresso3budget
Peppermint Tea3.25budget
Lemonade3.5budget
Hot Chocolate4standard
Cappuccino4.25standard
Latte4.5standard
Cold Brew4.75standard
Chai Latte4.75standard
Mocha5premium
Matcha Latte5.25premium

Count conditionally

SUM(CASE WHEN ... THEN 1 ELSE 0 END) counts matching rows, so one query can produce several counts side by side.

SELECT COUNT(*) AS orders,
       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;
Result on the Desk & Co. (online store) sample data (1 row)
ordersdeliveredshippedcancelled
10721

Custom sort order

Sort by business meaning instead of A–Z.

SELECT id, status
FROM orders
ORDER BY CASE status
           WHEN 'shipped' THEN 1
           WHEN 'delivered' THEN 2
           ELSE 3
         END, id;
Result on the Desk & Co. (online store) sample data (10 rows, first 6 shown)
idstatus
4shipped
8shipped
1delivered
2delivered
3delivered
6delivered

Common mistakes

Practice CASE WHEN interactively

Write real queries in your browser and get instant feedback in the lesson “CASE expressions” (Unit 7). New learners can start free from the first lesson.

Frequently asked questions

Is there an IF function in SQL?

CASE is the standard. MySQL also has IF(), SQL Server has IIF(), and SQLite has iif() in recent versions.

What is the short form of CASE?

CASE status WHEN 'shipped' THEN 1 ... END compares one value to a list of options, as in the sorting example above.

Related SQL tutorials