SQL CASE WHEN

WHEN checks a condition; THEN supplies the value to use if that condition is true — the core building block every CASE expression is made from.

What & Why

The full syntax is CASE WHEN condition THEN value END. Postgres checks condition for the current row; if it's true, the whole expression evaluates to value. The END keyword is mandatory — it's what tells Postgres the CASE expression is finished.

It helps to think of CASE WHEN ... THEN ... END as a single unit that behaves exactly like a column value once it's evaluated — you can give it a name with AS, just like any other column in SELECT.

See How It Works

BUSINESS QUESTION

Marketing wants to flag campaigns whose spend is at least 55,000, leaving the other rows as NULL.

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
Watch CASE classify campaign spendExample 1 of 4
CASE WHEN spend >= 55000 THEN 'high spend' END
namespendspend_flag
Spring Launch55000.00high spend
Retention Webinar45000.00?
Finance Retargeting50000.00?
Enterprise Search60000.00?

Spring Launch meets the WHEN condition, so CASE returns the first branch.

EXAMPLE QUERY
SELECT
  name,
  spend,
  CASE WHEN spend >= 55000 THEN 'high spend' END AS spend_flag
FROM marketing.campaigns
ORDER BY id;
Now You Try

Practice this concept

Marketing wants to flag campaigns whose spend is at least 55,000, leaving the other rows as NULL.

Available schema
marketing

Prefix tables with marketing.table_name.

namespendspend_flag
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