CASE: Choose a result with conditions
Core idea
CASE is an expression that chooses a value for each row. Use it to classify products or label scores without changing stored data. A searched CASE tests WHEN conditions in order and returns the THEN value for the first true condition.
Minimal example
SELECT CASE WHEN 2 > 1 THEN 'yes' ELSE 'no' END;Expected SQLite rows:
yesHow it works
Syntax: CASE WHEN condition THEN value ELSE fallback END. More WHEN clauses may appear before ELSE. FALSE and UNKNOWN do not match. If no condition matches and ELSE is omitted, the result is NULL. Simple CASE (CASE value WHEN match THEN result END) compares values for equality. In the shop example, prices below 200 cents are budget items; the others are regular items.
Practical example
SELECT id, CASE WHEN price_cents < 200 THEN 'budget' ELSE 'regular' END AS tier FROM products ORDER BY id;Expected SQLite rows:
1 | regular2 | budget3 | regular4 | budgetCommon mistake and practice
Put more specific conditions first when ranges overlap. Do not write WHEN NULL in a simple CASE to detect missingness; use WHEN score IS NULL in a searched CASE. Practice: classify prices below 200 as budget, 200–999 as standard, and 1000 or more as premium. Predict all four labels before running.