CASE: if-then logic inside a query

Label rows into bands and count different conditions side by side.

Module 5: Intermediate analysis · Lesson 17 of 26 · 15 min read · Free

CASE is SQL's IF statement. It checks conditions in order and returns the value for the first one that's true:

SELECT name, unit_price,
       CASE
         WHEN unit_price < 1000 THEN 'Budget'
         WHEN unit_price < 5000 THEN 'Standard'
         ELSE 'Premium'
       END AS price_band
FROM products
ORDER BY unit_price;

Indomie (₦250) is Budget; Golden Penny Spaghetti (₦1,050) is Standard; the four products at ₦5,000 or more — Ofada rice, the Samsung charger, Mama Gold rice and the Oraimo power bank — are Premium.

  • Conditions are checked top to bottom, and the first true one wins. That's why the second line can just say < 5000 — anything under 1,000 was already caught.
  • ELSE catches everything else. Without it, unmatched rows get NULL.
  • Always finish with END, and give the column an alias.

You can then group by the new column: GROUP BY price_band gives the number of products in each band.

Counting conditions side by side

This is the trick analysts use most. Put CASE inside SUM to count only matching rows:

Delivered and cancelled orders by channel
SELECT channel,
  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
GROUP BY channel;

One row per channel, with the statuses as columns — a mini pivot table. From here a cancellation rate is one step away: ROUND(100.0 * SUM(CASE WHEN status = 'Cancelled' THEN 1 ELSE 0 END) / COUNT(*), 1) AS cancel_pct. Walk-in orders are cancelled most often (6.3%).

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. What happens to rows that match no WHEN and there's no ELSE?

    • A They get NULL
    • B They get 0
    • C They are deleted
    • D An error occurs
    Show the answer

    A) They get NULL — Without ELSE, CASE returns NULL.

  2. In a CASE with several WHENs, which result is used?

    • A The first condition that is true
    • B The last condition that is true
    • C All of them
    • D The ELSE always
    Show the answer

    A) The first condition that is true — CASE stops at the first true condition.

  3. What does SUM(CASE WHEN status = 'Cancelled' THEN 1 ELSE 0 END) give?

    • A The number of cancelled orders
    • B The total value of cancelled orders
    • C The cancellation rate
    • D The number of statuses
    Show the answer

    A) The number of cancelled orders — It adds 1 for each cancelled row and 0 for every other row.

More free lessons: What SQL is, and why employers want it · Install DB Browser and open the practice database · WHERE: only the rows you need · COUNT, SUM, AVG, MIN and MAX · INNER JOIN: combine two tables · INSERT, UPDATE and DELETE — safely · From a business question to an answer