8. CASE WHEN: If-Then Logic in SQL
8.2 How to Write Simple CASE WHEN … THEN … ELSE
Why. One clear CASE pattern covers most label jobs.
What. CASE WHEN condition THEN value … ELSE value END
How. End with END. Alias the result column.
Steps
- Label Pune vs Other.
- Read WHEN top to bottom — first match wins.
- Always include ELSE when you can.
Examples
Example 1 · dataset: raja_coffee
SELECT order_id, city,
CASE WHEN city = 'Pune' THEN 'Home city'
ELSE 'Other city' END AS city_group
FROM orders
LIMIT 8;Output
| order_id | city | city_group |
|---|---|---|
| 1001 | Pune | Home city |
| 1002 | Mumbai | Other city |
| 1003 | Goa | Other city |
| 1004 | Pune | Home city |
| 1005 | Kolhapur | Other city |
| 1006 | Pune | Home city |
| 1007 | Nashik | Other city |
| 1008 | Solapur | Other city |
Meaning. Each row gets a rule-based label.
Ravindra Bagale's Tip
Forgot END? SQLite throws a syntax error near SELECT — add END.
Ravindra Bagale's Tip – मराठी
END विसरलात? Syntax error — END जोडा.
Ravindra Bagale's Tip – हिंदी
END भूले? Syntax error — END जोड़ें।