8. CASE WHEN: If-Then Logic in SQL
8.3 How to Bucket Amounts (Small / Medium / Large)
Why. Buckets turn raw money into Small/Medium/Large stories.
What. Chain WHEN amount thresholds from high to low (or low to high carefully).
How. WHEN >= 1000 THEN 'Large' WHEN >= 600 THEN 'Medium' ELSE 'Small'
Steps
- Pick thresholds that match the business.
- Order WHEN so the first true rule wins.
- Count rows per bucket with GROUP BY later.
Examples
Example 1 · dataset: raja_coffee
SELECT
CASE WHEN amount_inr >= 1000 THEN 'Large'
WHEN amount_inr >= 600 THEN 'Medium'
ELSE 'Small' END AS size,
COUNT(*) AS n
FROM orders
GROUP BY 1
ORDER BY n DESC;Output
| size | n |
|---|---|
| Medium | 13 |
| Small | 7 |
| Large | 4 |
Meaning. How many orders in each size bucket.
Ravindra Bagale's Tip
Put the strictest (largest) test first when using >= chains.
Ravindra Bagale's Tip – मराठी
>= साखळीत सर्वात मोठी/कडक अट आधी ठेवा.
Ravindra Bagale's Tip – हिंदी
>= चेन में सबसे सख्त (बड़ी) जाँच पहले रखें।