CASE WHEN — Conditional Logic
SQL's if-else statement — build custom categories, conditional columns, pivot tables, and handle complex branching logic directly inside any query
// Part 01
Why SQL Needs Conditional Logic
Every real business question involves conditional branching. A product is "High Margin" if its margin is above 40%, "Medium" if it is 25–40%, and "Low" otherwise. An order is "Fast" if delivered within 2 days, "Standard" if 3–5 days, "Slow" if more than 5 days. An employee is in the "Senior" band if their salary is above ₹60,000, otherwise "Junior."
None of these categories exist as columns in the database. They are derived from existing values using conditional logic. In every programming language this is an if-else statement. In SQL, it is the CASE WHEN expression.
CASE WHEN is one of the most powerful and frequently used constructs in SQL. It appears in SELECT for computed columns, in WHERE for complex filters, in ORDER BY for custom sort orders, and inside aggregate functions for conditional counting and summing. Mastering it unlocks an entire class of analytical queries that are impossible without it.
// Part 02
CASE WHEN Syntax — The Two Forms
CASE WHEN has two forms. The searched CASE evaluates a condition for each WHEN — the most flexible and most commonly used form. The simple CASE compares one expression against multiple values — a cleaner shorthand when comparing a single column.
Searched CASE — full conditional expressions
Simple CASE — comparing one value to many
The simple CASE is syntactic sugar for the searched CASE — CASE payment_method WHEN 'UPI' THEN ... is identical to CASE WHEN payment_method = 'UPI' THEN .... Use whichever reads more clearly for the specific situation. The searched CASE handles everything the simple CASE can, plus complex conditions that go beyond simple equality.
// Part 03
CASE WHEN in SELECT — Building Computed Categories
The most common use of CASE WHEN is inside SELECT to create a new computed column whose value depends on conditions evaluated for each row.
Loyalty tier display label
Product margin banding
Delivery speed classification
Order value tier
// Part 04
How CASE WHEN Evaluates — Short-Circuit Logic
CASE WHEN evaluates conditions top to bottom and returns the result for the first WHEN condition that is TRUE. Once a match is found, the remaining WHEN clauses are not evaluated — this is called short-circuit evaluation.
This behaviour is critical to understand for writing correct CASE expressions. Consider the margin bands query above. If a product has a 45% margin, it satisfies ALL three conditions:
Always order WHEN conditions from most specific to least specific — from the most restrictive condition to the most permissive. For range bands, order from highest threshold to lowest. For categories with overlap, put the more specific condition first.
ELSE — the default catch-all
The ELSE clause is optional. If a row matches no WHEN condition and there is no ELSE, the CASE expression returns NULL. This is a common silent bug — add an explicit ELSE to handle any unexpected values rather than letting them silently become NULL.
// Part 05
CASE WHEN in WHERE — Complex Conditional Filtering
CASE WHEN can appear in WHERE clauses to express filtering logic that would be extremely complex with AND/OR alone.
// Part 06
CASE WHEN in ORDER BY — Custom Sort Orders
CASE WHEN in ORDER BY lets you sort by a custom priority order rather than alphabetical or numeric order. This is essential when a business has a specific priority ranking that does not match any natural sort order.
// Part 07
CASE WHEN Inside Aggregate Functions — Conditional Aggregation
This is one of the most powerful SQL patterns — using CASE WHEN inside SUM, COUNT, or AVG to compute conditional aggregates. Instead of running multiple queries to count different subsets of data, you count all subsets in a single pass through the table.
Conditional COUNT — count rows matching different conditions
Conditional SUM — sum values only for matching rows
Pivot tables with CASE WHEN
Conditional aggregation is the SQL technique for creating pivot tables — transforming row values into columns. This is used constantly in reporting.
🎯 Pro Tip
Conditional aggregation — SUM(CASE WHEN condition THEN value ELSE 0 END) — is one of the highest-leverage SQL patterns in analytics. It replaces multiple queries with a single pass through the table, dramatically improving performance. Any time you are running the same query multiple times with different WHERE conditions and then combining the results in Excel, this pattern replaces all of that with one query.
// Part 08
CASE WHEN and NULL — Careful Handling
CASE WHEN interacts with NULL in two important ways: when testing for NULL inside WHEN conditions, and when the CASE expression itself returns NULL.
Testing for NULL inside CASE
Use IS NULL and IS NOT NULL inside WHEN conditions — never = NULL. The same rule from Module 11 applies inside CASE.
CASE returning NULL when no WHEN matches and no ELSE
Using COALESCE with CASE
When a CASE might return NULL and you want a default value, wrap the entire CASE in COALESCE:
// Part 09
Nested CASE WHEN — Multi-Dimensional Logic
CASE WHEN expressions can be nested — a THEN result can itself be another CASE expression. Use this sparingly — deeply nested CASE expressions become hard to read — but for two-dimensional logic it is sometimes the clearest approach.
// Part 10
Complete Business Analytics Examples
Here are complete, production-quality analytics queries that combine CASE WHEN with everything you have learned so far.
Full product performance dashboard
Customer segmentation report
// Part 11
What This Looks Like at Work
You are a senior analyst at Shopify. The finance team needs a weekly GMV (Gross Merchandise Value) report that breaks down revenue by order tier, payment method category, and delivery performance — all in a single table, one row per store. Previously this took three separate queries and manual Excel work. You build it as one CASE-driven query.
🎯 Pro Tip
Conditional aggregation — SUM(CASE WHEN ... END) inside GROUP BY — is what separates SQL analysts from SQL beginners. Once you internalise this pattern, you stop running three queries and combining them in Excel. You ask: "What conditions define each metric?" and write one CASE per metric inside one GROUP BY query. This is the single highest-leverage SQL skill for analytics work at Indian tech companies.
// Part 12
Interview Prep — 5 Questions With Complete Answers
CASE WHEN is SQL's conditional expression — equivalent to an if-else statement in programming languages. It evaluates a series of conditions in order and returns the result for the first condition that evaluates to TRUE. If no condition matches and there is an ELSE clause, the ELSE result is returned. If no condition matches and there is no ELSE, the expression returns NULL.
The searched CASE form evaluates arbitrary conditions for each WHEN: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default END. Each condition can be any Boolean expression — comparisons, range checks, IS NULL, BETWEEN, IN, even subqueries. This is the most flexible and commonly used form.
The simple CASE form compares one expression against multiple equality values: CASE expression WHEN value1 THEN result1 WHEN value2 THEN result2 ELSE default END. CASE payment_method WHEN 'UPI' THEN 'Digital' WHEN 'COD' THEN 'Cash' END is cleaner than CASE WHEN payment_method = 'UPI' THEN 'Digital' WHEN payment_method = 'COD' THEN 'Cash' END. The simple form is syntactic sugar — it is always equivalent to the searched form with equality conditions, but reads more cleanly when all conditions are simple equality checks on the same column.
CASE WHEN evaluates conditions strictly top to bottom and returns the result for the first condition that is TRUE — it does not evaluate subsequent conditions after finding a match. This is called short-circuit evaluation. The order of WHEN clauses is therefore critical to the correctness of the result.
The importance becomes clear with overlapping conditions. Consider classifying products by margin: a product with 45% margin satisfies both margin >= 0.25 and margin >= 0.40. If WHEN margin >= 0.25 THEN 'Medium' appears before WHEN margin >= 0.40 THEN 'High', the 45% margin product is classified as 'Medium' — incorrectly. The correct order puts the more restrictive condition first: WHEN margin >= 0.40 THEN 'High', then WHEN margin >= 0.25 THEN 'Medium'.
The professional rule: always order WHEN conditions from most specific (most restrictive) to least specific (most permissive). For numeric bands, put the highest threshold first. For boolean conditions with overlaps, put the more narrowly defined condition first. For conditions that are mutually exclusive (no overlap), order does not affect correctness but still matters for readability — put the most common or highest-priority case first. Testing your CASE expression against known edge cases — values that sit exactly at boundaries — is the most reliable way to verify the ordering is correct.
Conditional aggregation is the technique of computing multiple different aggregate values in a single query pass by using CASE WHEN inside aggregate functions like SUM, COUNT, and AVG. Instead of running three separate queries with different WHERE conditions and combining the results, you compute all three metrics simultaneously in one GROUP BY query.
The pattern for conditional SUM: SUM(CASE WHEN condition THEN value ELSE 0 END). For each row, if the condition is true the actual value contributes to the sum; if false, 0 contributes (adding nothing). The result is the sum of values only for rows where the condition was true. For conditional COUNT: SUM(CASE WHEN condition THEN 1 ELSE 0 END) — or equivalently COUNT(CASE WHEN condition THEN 1 END) which implicitly skips NULL (the no-ELSE form returns NULL which COUNT ignores).
A concrete example: to get total revenue, delivered revenue, and cancelled revenue in one query — SELECT SUM(total_amount) AS total, SUM(CASE WHEN status = 'Delivered' THEN total_amount ELSE 0 END) AS delivered, SUM(CASE WHEN status = 'Cancelled' THEN total_amount ELSE 0 END) AS cancelled FROM orders GROUP BY store_id. This single query replaces three queries. In data warehousing, this pattern is how pivot tables are built in SQL — each pivot column is one conditional aggregate. At Indian tech companies, conditional aggregation is used constantly for daily business reports, A/B test result analysis, funnel metrics, and any dashboard that shows data split by multiple categories simultaneously.
When no WHEN condition matches and the CASE expression has an ELSE clause, the ELSE result is returned. When no WHEN condition matches and there is no ELSE clause, the CASE expression returns NULL. This is the default behaviour defined by the SQL standard.
The danger of a missing ELSE is that it creates silent NULL values in the result. If a new value is added to a column — a new payment method, a new order status, a new product category — and the CASE expression does not have a WHEN for that value and has no ELSE, the new rows produce NULL in the computed column with no error or warning. This corrupts aggregations (SUM treats NULL as 0-excluded, AVG ignores NULLs), breaks application code that expects a non-null value, and produces misleading reports.
The professional practice: always include an ELSE in every CASE expression. For categorisation use ELSE 'Other' or ELSE 'Unknown' — this makes unexpected values visible. For numeric defaults use ELSE 0. For boolean logic use ELSE FALSE. The ELSE clause acts as a safety net: it guarantees that the CASE expression never returns NULL from a missing match, and makes unexpected values immediately visible in the output rather than silently missing. The only acceptable case for omitting ELSE is when you genuinely want NULL for unmatched rows and your downstream processing handles NULL correctly — which should be explicitly documented in a comment.
Yes, CASE WHEN can be used inside ORDER BY to sort by a custom priority order rather than the natural alphabetical or numeric order of a column's values. This is one of the most useful applications of CASE WHEN in reporting contexts where business priority does not align with alphabetical or numeric sort order.
The technique: assign a numeric rank to each value using CASE WHEN and sort by that rank. ORDER BY CASE status WHEN 'Processing' THEN 1 WHEN 'Returned' THEN 2 WHEN 'Delivered' THEN 3 WHEN 'Cancelled' THEN 4 ELSE 5 END sorts orders by business priority — actionable statuses first — rather than alphabetically (Cancelled, Delivered, Processing, Returned). The numbers 1-4 are invisible in the output; they only control the sort order.
Another common example: sorting loyalty tiers by tier value (Platinum, Gold, Silver, Bronze) rather than alphabetically (Bronze, Gold, Platinum, Silver). ORDER BY CASE loyalty_tier WHEN 'Platinum' THEN 1 WHEN 'Gold' THEN 2 WHEN 'Silver' THEN 3 WHEN 'Bronze' THEN 4 END. This can be combined with additional sort keys: ORDER BY CASE loyalty_tier... END ASC, joined_date DESC — sort by tier priority first, then by most recently joined within each tier. CASE in ORDER BY is also used to put specific rows at the top or bottom: ORDER BY CASE WHEN customer_id = 42 THEN 0 ELSE 1 END sorts one specific row to the top of any result regardless of other sort criteria.
// Part 13
Errors You Will Hit — And Exactly Why They Happen
🎯 Key Takeaways
- ✓CASE WHEN is SQL's if-else expression. It evaluates conditions top to bottom and returns the result for the first TRUE condition. It can appear in SELECT, WHERE, ORDER BY, and inside aggregate functions.
- ✓Two forms: searched CASE (CASE WHEN condition THEN result) for arbitrary conditions, and simple CASE (CASE expression WHEN value THEN result) for equality checks against one column. Both produce identical results for equality conditions.
- ✓Evaluation is top-to-bottom with short-circuit: the first matching WHEN wins and remaining WHENs are skipped. Order WHEN conditions from most restrictive to least restrictive.
- ✓Always include ELSE. Without it, unmatched rows return NULL silently — breaking aggregations, application code, and reports. Use ELSE 'Other', ELSE 0, or ELSE FALSE as appropriate.
- ✓CASE WHEN in ORDER BY enables custom sort priorities: ORDER BY CASE status WHEN 'Processing' THEN 1 WHEN 'Delivered' THEN 2 END — sorts by business priority, not alphabetically.
- ✓Conditional aggregation — SUM(CASE WHEN condition THEN value ELSE 0 END) — computes multiple metrics in one query pass. It replaces running the same query repeatedly with different WHERE conditions.
- ✓Pivot tables in SQL use conditional aggregation: each pivot column is one CASE WHEN inside SUM or COUNT, grouped by the row dimension.
- ✓NULL handling inside CASE: use IS NULL and IS NOT NULL in WHEN conditions — never = NULL. When the column being tested is NULL, all comparisons return NULL and no WHEN matches.
- ✓All THEN and ELSE results must be the same data type or implicitly castable to a common type. Mixing text and numeric results causes a type error.
- ✓Conditional aggregation is the highest-leverage CASE WHEN skill for analytics. Any report that shows data split by multiple categories simultaneously uses this pattern — master it and you eliminate entire categories of manual Excel work.
What comes next
In Module 18, you learn about data types in SQL — what types exist, which to use for which data, and how type mismatches cause silent bugs in calculations and comparisons.
Module 18 → SQL Data TypesDiscussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.