CASE expression

Also known as: CASE WHEN

On this page 7

The CASE expression is the standard SQL construct for conditional logic inside a query: it evaluates a list of conditions in order and returns the value of the first one that is true, or a default value when none matches. Because it is an expression, not a statement, it can appear almost anywhere a value is allowed, including the select list, WHERE, ORDER BY, GROUP BY and inside an aggregate function.

Often written informally as CASE WHEN, the construct is defined in the ISO SQL standard and supported by every major relational database. It is the portable way to express if-then-else rules in declarative SQL, replacing vendor-specific functions such as DECODE or IIF in most situations.

Searched and simple forms of the CASE expression

The CASE expression comes in two syntactic forms. The searched form tests an independent Boolean condition in each branch, while the simple form compares one operand for equality against a list of values.

A searched example reads CASE WHEN amount >= 1000 THEN 'large' WHEN amount >= 100 THEN 'medium' ELSE 'small' END. The equivalent simple form works only for equality, for example CASE status WHEN 'A' THEN 'Active' WHEN 'C' THEN 'Closed' ELSE 'Unknown' END.

PropertySimple CASESearched CASE
Test performedEquality against one operandAny Boolean condition
Ranges and inequalitiesNot supportedSupported
Different columns per branchNot supportedSupported
NULL matchingNever matches NULLPossible with IS NULL
Readability for code listsVery compactMore verbose
The two forms of the CASE expression compared

The NULL row deserves attention. A simple CASE uses equality, and NULL = NULL is not true in SQL, so a branch such as WHEN NULL THEN never fires. To handle missing values, the searched form with WHEN col IS NULL THEN is required.

How SQL evaluates a CASE expression

SQL evaluates the WHEN conditions from top to bottom and returns the result of the first true condition. Later branches are ignored for that row, so the order of the branches is part of the logic: overlapping ranges must be listed from the most specific to the most general.

When no condition is true and no ELSE clause exists, the expression returns NULL implicitly. This silent default is a common source of wrong reports, because rows that fall outside every branch disappear from counts or appear as empty labels without any error.

All branches must produce values of a compatible data type. The database derives one result type from all THEN and ELSE values, so mixing a number in one branch and text in another either raises a conversion error or forces an implicit cast that differs between products.

RulePractical effectRecommended habit
First match winsOverlapping branches shadow later onesOrder conditions from narrow to broad
Missing ELSE returns NULLUnmatched rows vanish silentlyAlways write an explicit ELSE
Common result typeMixed types cause errors or castsReturn one type in every branch
Short-circuit behaviorUsually stops at the first true branchDo not rely on it to avoid errors in aggregates
Evaluation rules and their practical effect

The short-circuit rule has exceptions. Most databases stop evaluating once a branch matches, but optimizers may compute constant subexpressions or aggregates early. A guard such as CASE WHEN x = 0 THEN NULL ELSE 1 / x END is reliable for row values, yet it should not be trusted to protect an aggregate computed in the same branch.

Typical uses of CASE in queries

The CASE expression is most valuable where a query must classify, reshape or conditionally count rows without a second pass over the data. The following patterns cover the majority of real use.

PatternWhere CASE appearsPurpose
BucketingSELECT list and GROUP BYGroup values into ranges or bands
Conditional aggregationInside SUM or COUNTCount several categories in one pass
PivotingOne aggregate per output columnTurn row values into columns
Custom sort orderORDER BYSort by business priority, not alphabet
Conditional updateSET clause of UPDATEApply different changes per row
Label translationSELECT listTurn codes into readable text
Common query patterns built with CASE

Conditional aggregation is the most powerful pattern. An expression such as SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) next to a similar sum for refunds produces a complete summary in a single table scan, where separate subqueries would read the table several times.

In an UPDATE, one CASE can replace several statements, for example raising prices by different percentages per category. This keeps the change atomic in one statement and avoids partial updates if a later statement fails.

Several shorter functions are defined in terms of CASE and are worth preferring when they express the intent exactly. Using them improves readability without changing results.

ConstructEquivalent CASE logicPortability
COALESCE(a, b)WHEN a IS NOT NULL THEN a ELSE bISO standard, universal
NULLIF(a, b)WHEN a = b THEN NULL ELSE aISO standard, universal
FILTER clause on aggregatesAggregate over CASE with no ELSEStandard, limited product support
DECODESimple CASE with equalityVendor-specific
IIFSearched CASE with two branchesVendor-specific
Shorthand functions and their CASE equivalents

CASE should not be confused with procedural CASE statements found in stored procedure languages, which control program flow rather than return a value. When a mapping grows to dozens of codes or changes often, a lookup table joined to the query is usually cleaner than a long CASE, because the rules become data that can be maintained without editing SQL.

Performance and maintainability considerations

The CASE expression itself is cheap to evaluate, but its placement affects performance. A CASE wrapped around a column in a WHERE clause usually makes the predicate non-sargable, so the optimizer cannot use an index on that column and falls back to scanning rows.

  • Rewrite filters as plain predicates combined with OR when an index should be used.
  • Repeating a long CASE in SELECT and GROUP BY invites inconsistency; compute it once in a CTE or subquery.
  • Keep business thresholds in one documented place so that reports do not drift apart.

The simple explanation

A CASE expression lets a database answer an if-then question for each row. It works like a sorting clerk with a short checklist. For every item, the clerk reads the rules from the top. The first rule that fits decides the label. If nothing fits, the clerk uses a default label.

This lets one query turn raw numbers into categories such as small, medium and large. It saves writing several separate queries.

How it is used in practice

A subscription business wants a monthly report showing how many customers are new, active, at risk or lost. Its analyst writes one query over the customer table. A CASE expression labels each customer: no purchase in 90 days means lost, no purchase in 30 days means at risk, a first purchase within the month means new, and everyone else is active.

The same query then uses conditional aggregation to count each group per region in one pass over about 4 million rows. Earlier, the team ran four separate queries that took several minutes in total and occasionally disagreed because each used slightly different date logic. With the shared CASE, the categories are consistent and the report runs in under a minute.