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.

Now You Try

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.

Available schema
saas

Prefix tables with saas.table_name.

namemrrmrr_tier
saas.accounts
ColumnType
idinteger
nametext
plantext
mrrnumeric
created_attimestamp with time zone
churned_attimestamp with time zone
countrytext
employee_countinteger
industrytext
customer_segment_v2text
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario