Conditional logic & CASE
Concept  ·  SQL & Querying

CASE takes the first matching WHEN — overlapping conditions must be ordered narrowest-first, or the wide arm swallows the boundary.

WHEN arms are not a lookup table, they are a corridor — the row walks past each condition and exits at the first TRUE. With ranges that nest (>= 20 contains >= 45), the wide door first means the narrow door never opens, and nothing warns you: every row still gets a tier, just sometimes the wrong one, densest exactly at the boundaries.

See it break
batches
batchcure_days
b160
b230
b310
The trap
SELECT
  batch,
  CASE
    WHEN cure_days >= 20 THEN 'standard'
    WHEN cure_days >= 45 THEN 'premium'
    ELSE 'quick'
  END AS grade
FROM
  batches
ORDER BY
  batch;
The fix
SELECT
  batch,
  CASE
    WHEN cure_days >= 45 THEN 'premium'
    WHEN cure_days >= 20 THEN 'standard'
    ELSE 'quick'
  END AS grade
FROM
  batches
ORDER BY
  batch;
INPUTYour queryThe fix
b1standardpremium
b2standardstandard
b3quickquick

A 60-day batch graded 'standard' and the top 'premium' tier stayed empty — CASE takes the first matching WHEN, so the wide arm listed first swallowed the boundary.

The rule

Order the arms narrowest-first, or write closed ranges (BETWEEN 20 AND 44) so the arms can't overlap and any order works.

Shows up elsewhere
CASE without ELSE is NULLBETWEEN on timestamps — the midnight trap
Try one →Prove it in practice →