SQL Nested CASE

A full CASE expression can live inside a THEN or ELSE branch of another CASE — useful for genuinely two-level classification.

What & Why

Since a CASE expression evaluates to an ordinary value, nothing stops another CASE expression from being used as that value. This lets one condition decide broadly, and a second, nested condition refine the answer further — genuinely useful when a classification has two independent dimensions rather than one flat list of categories.

See How It Works

BUSINESS QUESTION

Marketing wants active campaigns split into high- and standard-spend labels, while every inactive campaign keeps one fallback label.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT
  id AS campaign_id,
  name,
  CASE
    WHEN status = 'active' THEN
      CASE
        WHEN spend >= 10000 THEN 'active — high spend'
        ELSE 'active — standard spend'
      END
    ELSE 'not active'
  END AS campaign_label
FROM marketing.campaigns
ORDER BY campaign_id;
RESULT — exact output from the displayed Queryflo rows
campaign_idnamecampaign_label
1Spring Launchactive — high spend
2Retention Webinaractive — high spend
3Finance Retargetingactive — high spend
4Enterprise Searchactive — high spend

All displayed campaigns are active and have spend above the nested threshold.

Now You Try

Practice this concept

Marketing wants active campaigns split into high- and standard-spend labels while inactive campaigns share one fallback label.

Available schema
marketing

Prefix tables with marketing.table_name.

campaign_idnamecampaign_label
marketing.campaigns
ColumnType
idinteger
nametext
channeltext
spendnumeric
start_datedate
end_datedate
statustext
target_segmenttext
legacy_idtext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario