← Back to SQL, page 25

sql-0499 · Easy fresher

A discount query assigns every order to the 'standard' tier although some orders are over 500. Why does the CASE expression ignore the larger tiers?

CASE returns the result of the first WHEN condition that is true and stops. If a broad condition such as total > 0 comes first, larger totals never reach later branches. Order the conditions from most specific to least specific, or use non-overlapping ranges.

Full answer
sql
CREATE TABLE tier_orders (id INTEGER PRIMARY KEY, total INTEGER);
INSERT INTO tier_orders VALUES (1, 80), (2, 300), (3, 750), (4, 0);

The query as written:

sql
SELECT id, total, CASE WHEN total > 0 THEN 'standard' WHEN total > 250 THEN 'silver' WHEN total > 500 THEN 'gold' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;
idtotaltier
180standard
2300standard
3750standard
40none

Every positive total matches the first condition, so 'silver' and 'gold' can never be reached. The ELSE branch is used only for the zero total.

A corrected version:

sql
SELECT id, total, CASE WHEN total > 500 THEN 'gold' WHEN total > 250 THEN 'silver' WHEN total > 0 THEN 'standard' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;
idtotaltier
180standard
2300silver
3750gold
40none

Testing the strictest condition first gives gold for 750, silver for 300, standard for 80 and none for 0. The same first-match rule applies to CASE in PostgreSQL. For tiers that live in data, a small lookup table of thresholds joined with a range condition is easier to change than editing a CASE expression, and unit tests should include a value in each band and each boundary.

sql
CREATE TABLE tier_orders (id INTEGER PRIMARY KEY, total INTEGER);
INSERT INTO tier_orders VALUES (1, 80), (2, 300), (3, 750), (4, 0);

SELECT id, total, CASE WHEN total > 0 THEN 'standard' WHEN total > 250 THEN 'silver' WHEN total > 500 THEN 'gold' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;

SELECT id, total, CASE WHEN total > 500 THEN 'gold' WHEN total > 250 THEN 'silver' WHEN total > 0 THEN 'standard' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CASE stops at the first true condition
  • Order conditions from most to least specific
  • Test every band and boundary
  • Lookup tables suit changing thresholds

Common mistakes

  • Putting the broadest condition first
  • Leaving boundaries untested

Follow-ups

  • How would a threshold table express the same tiers?
  • What does CASE return when no branch matches and ELSE is missing?

Tips

  • Walk one value through the branches