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.
| Property | Simple CASE | Searched CASE |
|---|---|---|
| Test performed | Equality against one operand | Any Boolean condition |
| Ranges and inequalities | Not supported | Supported |
| Different columns per branch | Not supported | Supported |
| NULL matching | Never matches NULL | Possible with IS NULL |
| Readability for code lists | Very compact | More verbose |
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.
| Rule | Practical effect | Recommended habit |
|---|---|---|
| First match wins | Overlapping branches shadow later ones | Order conditions from narrow to broad |
| Missing ELSE returns NULL | Unmatched rows vanish silently | Always write an explicit ELSE |
| Common result type | Mixed types cause errors or casts | Return one type in every branch |
| Short-circuit behavior | Usually stops at the first true branch | Do not rely on it to avoid errors in aggregates |
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.
| Pattern | Where CASE appears | Purpose |
|---|---|---|
| Bucketing | SELECT list and GROUP BY | Group values into ranges or bands |
| Conditional aggregation | Inside SUM or COUNT | Count several categories in one pass |
| Pivoting | One aggregate per output column | Turn row values into columns |
| Custom sort order | ORDER BY | Sort by business priority, not alphabet |
| Conditional update | SET clause of UPDATE | Apply different changes per row |
| Label translation | SELECT list | Turn codes into readable text |
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.
CASE compared with related SQL constructs
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.
| Construct | Equivalent CASE logic | Portability |
|---|---|---|
| COALESCE(a, b) | WHEN a IS NOT NULL THEN a ELSE b | ISO standard, universal |
| NULLIF(a, b) | WHEN a = b THEN NULL ELSE a | ISO standard, universal |
| FILTER clause on aggregates | Aggregate over CASE with no ELSE | Standard, limited product support |
| DECODE | Simple CASE with equality | Vendor-specific |
| IIF | Searched CASE with two branches | Vendor-specific |
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.