Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 03 / Topic 9 of 9

CASE expressions

CASE is SQL's if/else — it buckets values right inside the query:

SELECT name, price,
       CASE
         WHEN price >= 500 THEN 'premium'
         WHEN price >= 100 THEN 'mid'
         ELSE 'budget'
       END AS price_band
FROM products
ORDER BY price DESC;
        name        |  price  | price_band 
--------------------+---------+------------
 Laptop Pro 14      | 1200.00 | premium
 Laptop Air 13      |  950.00 | premium
 Phone X            |  799.00 | premium
 Phone Lite         |  399.00 | mid
 Coffee Maker       |  120.00 | mid
 Chef Knife         |   80.00 | budget
 Postgres Deep Dive |   55.00 | budget
 Desk Lamp          |   45.00 | budget
 SQL for Beginners  |   35.00 | budget
 USB-C Cable        |   15.00 | budget
(10 rows)

Conditions are checked top-down and the first match wins — so the 1200.00 laptop is premium, never also mid. Without an ELSE, non-matches get NULL.

There is also a compact form for matching one expression against values:

SELECT order_id, status,
       CASE status
         WHEN 'delivered' THEN '✓ done'
         WHEN 'cancelled' THEN '✗ lost'
         ELSE '… in motion'
       END AS board_label
FROM orders
ORDER BY order_id
LIMIT 5;
 order_id |  status   | board_label 
----------+-----------+-------------
        1 | delivered | ✓ done
        2 | delivered | ✓ done
        3 | delivered | ✓ done
        4 | shipped   | … in motion
        5 | cancelled | ✗ lost
(5 rows)

CASE works anywhere an expression works — in ORDER BY for custom sort orders, and (next part) inside aggregates, where it becomes the key to conditional counting.

🧪 Quick quiz — answer from memory, then check.

  1. In a CASE, a row matches two WHEN conditions. Which applies?
  2. What does a CASE without ELSE return for a non-matching row?
Show the answers
  1. The first one, top-down — later matches are never checked.
  2. NULL.

Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.

Search the guide