All SQL topics
SQL TOPIC

SQL CASE WHEN: create categories and conditional totals

CASE WHEN works like IF in a spreadsheet: it labels rows or counts only some of them.

CASE WHEN price >= 300 THEN 'premium' ELSE 'standard' END creates a new category column.

SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) counts refunds inside a grouped query, which makes shares and rates easy.

Worked example

Label each product as premium (€300 or more) or standard.

SELECT name,
  CASE WHEN price >= 300 THEN 'premium' ELSE 'standard' END AS tier
FROM products
ORDER BY price DESC
LIMIT 6;
Result on the sample data
nametier
14-inch laptoppremium
Mini PCpremium
Standing deskpremium
Ergonomic chairpremium
27-inch monitorpremium
Noise-cancelling headphonesstandard

Common mistakes

  • Forgetting ELSE, which leaves NULL for every unmatched row.
  • Overlapping conditions: CASE uses the first one that matches.