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;| id | total | tier |
|---|---|---|
| 1 | 80 | standard |
| 2 | 300 | standard |
| 3 | 750 | standard |
| 4 | 0 | none |
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;| id | total | tier |
|---|---|---|
| 1 | 80 | standard |
| 2 | 300 | silver |
| 3 | 750 | gold |
| 4 | 0 | none |
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