SQL CASE
SQL's if/then/else — lets a query make a decision for each row, and return a different value depending on the answer.
What & Why
CASE evaluates conditions from top to bottom and returns the first matching result. Here each saas.accounts.mrr value becomes a high, mid, or low reporting tier without changing the stored account row.
Branch order matters: mrr >= 200 must come before mrr >= 150, because every high-MRR account also satisfies the broader mid threshold.
See How It Works
SaaS leadership wants accounts bucketed by MRR tier.
| id | name | plan | mrr | created_at | churned_at | country | employee_count | industry |
|---|---|---|---|---|---|---|---|---|
| 1 | Acme Labs | growth | 240.00 | 2024-01-08 10:00:00+00 | NULL | US | 45 | software |
| 2 | Northstar Co | starter | 90.00 | 2024-02-12 09:30:00+00 | 2024-05-18 12:00:00+00 | CA | 18 | services |
| 3 | Atlas Works | scale | 480.00 | 2024-03-04 15:10:00+00 | NULL | GB | 120 | manufacturing |
| 4 | Bright Path | growth | 180.00 | 2024-04-19 11:45:00+00 | NULL | US | 62 | education |
SELECT
name,
mrr,
CASE
WHEN mrr >= 200 THEN 'high'
WHEN mrr >= 150 THEN 'mid'
ELSE 'low'
END AS mrr_tier
FROM saas.accounts
ORDER BY id;| name | mrr | mrr_tier |
|---|---|---|
| Acme Labs | 240.00 | high |
| Northstar Co | 90.00 | low |
| Atlas Works | 480.00 | high |
| Bright Path | 180.00 | mid |
CASE classifies the four displayed saas.accounts rows in source order.
Practice this concept
SaaS leadership wants each account classified by MRR: high at 200 or more, mid at 150 or more, and low otherwise. Return name, mrr, and mrr_tier in account-id order.
saasPrefix tables with saas.table_name.
namemrrmrr_tiersaas.accounts| Column | Type |
|---|---|
| id | integer |
| name | text |
| plan | text |
| mrr | numeric |
| created_at | timestamp with time zone |
| churned_at | timestamp with time zone |
| country | text |
| employee_count | integer |
| industry | text |
| customer_segment_v2 | text |
Sign up free to try it on a real business scenario