SQL · Module 5 · Lesson 41 min read

CASE Expressions

Searched CASE (most common)

SQL
CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ELSE default_result
END
  • Conditions are checked top to bottom; the first true one wins
  • Without ELSE, unmatched rows get NULL
  • All results should be the same type

Simple CASE (compare one value)

SQL
CASE city
  WHEN 'Kathmandu' THEN 'Valley'
  WHEN 'Lalitpur'  THEN 'Valley'
  ELSE 'Outside'
END

⚠️ The simple form can't match NULL (WHEN NULL never matches) — use CASE WHEN city IS NULL …

Where you can use CASE

  • SELECT – labels and buckets: 'Small' / 'Medium' / 'Large'
  • ORDER BY – custom sort order: urgent first
  • WHERE – complex conditional filters (but plain AND/OR is often clearer)
  • UPDATE … SET – conditional updates
  • Inside aggregates – conditional counts and sums (a "pivot"): sum(CASE WHEN category_id = 7 THEN amount ELSE 0 END) AS groceries (PostgreSQL also has FILTER (WHERE …), Unit 6)
  • GROUP BY – group by the bucket

Tips

  • Order WHEN branches from most specific to least specific
  • For long fixed mappings, a lookup table + JOIN is easier to maintain than a giant CASE

Example

SQL
-- Bucket expenses by size
SELECT title, amount,
       CASE
         WHEN amount >= 5000 THEN '🔴 Large'
         WHEN amount >= 1500 THEN '🟡 Medium'
         ELSE '🟢 Small'
       END AS size
FROM expenses
WHERE user_id = 1
ORDER BY amount DESC;

-- Simple CASE + handling NULL
SELECT name,
       CASE city
         WHEN 'Kathmandu' THEN 'Valley'
         WHEN 'Lalitpur'  THEN 'Valley'
         ELSE 'Outside valley'
       END AS region,
       CASE WHEN city IS NULL THEN 'City not set' ELSE city END AS city_label
FROM users;

-- Count per bucket
SELECT CASE WHEN amount >= 5000 THEN 'Large'
            WHEN amount >= 1500 THEN 'Medium'
            ELSE 'Small' END AS size,
       count(*), sum(amount)
FROM expenses
GROUP BY 1
ORDER BY sum(amount) DESC;

-- Pivot: one row per user, one column per month
SELECT user_id,
       sum(CASE WHEN spent_on < '2026-10-01' THEN amount ELSE 0 END)                   AS sep,
       sum(CASE WHEN spent_on >= '2026-10-01' AND spent_on < '2026-11-01' THEN amount ELSE 0 END) AS oct,
       sum(CASE WHEN spent_on >= '2026-11-01' THEN amount ELSE 0 END)                  AS nov
FROM expenses
GROUP BY user_id
ORDER BY user_id;
--  1 | 6050.00 | 8820.00 | 7100.00 ...

-- Custom sort: unpaid bills due soonest first, then paid ones
SELECT title, due_date, paid FROM bills
ORDER BY CASE WHEN paid THEN 1 ELSE 0 END, due_date;