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

BUSINESS QUESTION

SaaS leadership wants accounts bucketed by MRR tier.

idnameplanmrrcreated_atchurned_atcountryemployee_countindustry
1Acme Labsgrowth240.002024-01-08 10:00:00+00NULLUS45software
2Northstar Costarter90.002024-02-12 09:30:00+002024-05-18 12:00:00+00CA18services
3Atlas Worksscale480.002024-03-04 15:10:00+00NULLGB120manufacturing
4Bright Pathgrowth180.002024-04-19 11:45:00+00NULLUS62education
EXAMPLE QUERY
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;
RESULT — exact output from the displayed Queryflo rows
namemrrmrr_tier
Acme Labs240.00high
Northstar Co90.00low
Atlas Works480.00high
Bright Path180.00mid

CASE classifies the four displayed saas.accounts rows in source order.

Intermediate business practice

Sign up free to try it on a real business scenario