Deriving a Category with SQL CASE

A CASE expression chooses one result from branch conditions. Order and completeness determine how overlapping and unmatched rows are handled.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a quantity label
  2. Handle null explicitly
  3. Place overlapping conditions in priority order
  4. Check exact thresholds and unknown inputs

Trace a quantity label

A CASE can label at least 100 as large, at least 25 as medium, and remaining valid quantities as small. Testing the bigger threshold first protects the large case. See classification thresholds.

Handle null explicitly

An ordinary threshold comparison with null may never be true. If missing quantity is meaningful, label it separately before using a catch-all branch. Null and zero explain why the default matters.[1]

Place overlapping conditions in priority order

A case expression can label scores of at least ninety top and scores of at least seventy pass. Ninety-two satisfies both comparisons, so the top branch needs to be earlier if that is the label intended. See conditional chains.

WITH scores(score) AS (VALUES (65),(75),(92))
SELECT score, CASE WHEN score >= 90 THEN 'top' WHEN score >= 70 THEN 'pass' ELSE 'low' END
FROM scores ORDER BY score;
-- Expected: low, pass, top in score order.

Check exact thresholds and unknown inputs

Add scores seventy and ninety to test boundary inclusion. A null input may reach the fallback because neither comparison is true. Define a separate label if missing scores need to remain visible.

References

  1. PostgreSQL Global Development Group, Queries ↩