SQL CASE WHEN Explained
Level: intermediate · ~17 min read · Intent: informational
Audience: backend developers, data analysts, data engineers, technical teams, students, operations teams
Prerequisites
- basic familiarity with databases
- basic understanding of SELECT, WHERE, and SQL conditions
Key takeaways
- SQL CASE WHEN lets you add conditional logic directly inside queries, which makes it one of the most useful tools for labeling, categorizing, transforming, and summarizing data.
- The most important CASE WHEN skill is not just syntax. It is knowing where to use it well, especially in SELECT lists, conditional aggregates, UPDATE statements, ORDER BY logic, and business-rule reporting.
FAQ
- What does CASE WHEN do in SQL?
- CASE WHEN adds conditional logic to a SQL query. It lets you return different values depending on whether one or more conditions are true.
- What is the difference between simple CASE and searched CASE in SQL?
- Simple CASE compares one expression against multiple possible values, while searched CASE evaluates full boolean conditions such as greater than, less than, and combined logical checks.
- Can you use CASE WHEN in a WHERE clause?
- Yes, but it is often clearer to write the condition directly in WHERE when possible. CASE WHEN is more commonly used in SELECT, ORDER BY, GROUP BY, aggregates, and UPDATE statements.
- Does SQL CASE WHEN stop at the first match?
- Yes. CASE WHEN evaluates conditions in order and returns the result for the first matching condition, then stops checking the rest.
SQL CASE WHEN is one of the most useful tools in SQL because it lets you add logic directly into a query.
Without CASE, SQL mostly does this:
- return rows
- filter rows
- sort rows
- join rows
- aggregate rows
With CASE, SQL starts doing things like:
- label customers as high value or low value
- convert numeric scores into pass or fail
- group orders into price ranges
- turn status codes into readable categories
- count only rows that match a condition
- and update values differently depending on business rules
That is why CASE WHEN matters so much.
It is how SQL becomes more expressive. It lets you move from:
- raw data retrieval to
- logic-driven reporting and transformation
This guide explains SQL CASE WHEN clearly, including syntax, common patterns, conditional aggregation, ordering, grouping, updates, and the mistakes beginners make most often.
Why SQL CASE WHEN matters
A lot of real SQL work depends on conditional logic.
For example, you may want to answer questions like:
- which customers are premium?
- which orders are overdue?
- which products are low stock?
- which scores count as excellent, good, average, or poor?
- how many paid orders versus unpaid orders do we have?
- what label should appear for each status code?
Those questions are hard to answer with raw columns alone.
That is where CASE WHEN becomes valuable.
It lets you define rules inside SQL such as:
- if this is true, return one value
- otherwise, return another value
That sounds simple, but it makes a huge amount of reporting and data transformation possible.
The most important rule
Before going into syntax, remember this:
SQL CASE WHEN evaluates conditions in order and returns the result for the first match.
That matters because the order of your conditions changes the result.
For example:
CASE
WHEN score >= 50 THEN 'Pass'
WHEN score >= 80 THEN 'Distinction'
ELSE 'Fail'
END
This is wrong for high scores because:
- a score of 90 matches
score >= 50first - SQL returns
'Pass' - it never reaches
'Distinction'
The correct order is:
CASE
WHEN score >= 80 THEN 'Distinction'
WHEN score >= 50 THEN 'Pass'
ELSE 'Fail'
END
That one rule explains many CASE-related bugs.
What SQL CASE WHEN is
CASE WHEN is SQL’s way of expressing conditional logic.
It works a bit like:
if / else if / else
in programming languages.
It checks conditions and returns a value depending on which condition matches.
At a high level:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END
This means:
- if
condition1is true, returnresult1 - otherwise, if
condition2is true, returnresult2 - otherwise, return
default_result
That is the core pattern.
The two main forms of CASE in SQL
There are two common CASE styles:
- simple CASE
- searched CASE
Both are useful, but searched CASE is more common in practice.
1. Simple CASE
Simple CASE compares one expression against several possible values.
Pattern:
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
ELSE default_result
END
Example:
SELECT
order_id,
status_code,
CASE status_code
WHEN 'P' THEN 'Pending'
WHEN 'S' THEN 'Shipped'
WHEN 'D' THEN 'Delivered'
ELSE 'Unknown'
END AS status_label
FROM orders;
This means:
- if
status_codeisP, returnPending - if
status_codeisS, returnShipped - if
status_codeisD, returnDelivered - otherwise return
Unknown
This form is great when you are matching one column to fixed known values.
2. Searched CASE
Searched CASE uses full conditions.
Pattern:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END
Example:
SELECT
student_id,
score,
CASE
WHEN score >= 80 THEN 'Excellent'
WHEN score >= 60 THEN 'Good'
WHEN score >= 50 THEN 'Pass'
ELSE 'Fail'
END AS grade_band
FROM exam_results;
This is more flexible because each WHEN can use a full boolean condition.
That makes searched CASE the version you will use most often in real SQL work.
CASE WHEN in a SELECT statement
The most common place to use CASE WHEN is inside the SELECT list.
This lets you create calculated or labeled columns in the output.
Example:
SELECT
employee_name,
salary,
CASE
WHEN salary >= 100000 THEN 'High'
WHEN salary >= 60000 THEN 'Medium'
ELSE 'Low'
END AS salary_band
FROM employees;
This query adds a new output column called salary_band.
The original data is unchanged. You are just presenting it with additional logic.
This is one of the most practical uses of CASE.
Example: labeling order status
SELECT
order_id,
order_date,
shipped_date,
CASE
WHEN shipped_date IS NULL THEN 'Not Shipped'
ELSE 'Shipped'
END AS shipping_status
FROM orders;
This is useful when the source data stores raw values but you want the result to be easier to read.
Example: marking overdue invoices
SELECT
invoice_id,
due_date,
paid_date,
CASE
WHEN paid_date IS NOT NULL THEN 'Paid'
WHEN due_date < CURRENT_DATE THEN 'Overdue'
ELSE 'Open'
END AS invoice_status
FROM invoices;
This is a strong real-world CASE pattern:
- first handle paid invoices
- then handle overdue unpaid invoices
- then treat the rest as open
This kind of prioritization logic is exactly where CASE is useful.
CASE WHEN with multiple conditions
You can combine conditions using:
ANDOR- parentheses
Example:
SELECT
customer_id,
country,
total_spend,
CASE
WHEN country = 'USA' AND total_spend >= 1000 THEN 'US Premium'
WHEN country = 'UK' AND total_spend >= 800 THEN 'UK Premium'
ELSE 'Standard'
END AS customer_segment
FROM customers;
This lets you model more realistic business rules.
It is especially useful when categories depend on more than one column.
CASE WHEN with NULL values
NULL handling is a very common CASE use case.
Example:
SELECT
employee_name,
bonus,
CASE
WHEN bonus IS NULL THEN 'No Bonus'
ELSE 'Has Bonus'
END AS bonus_status
FROM employees;
This works because CASE handles boolean conditions like any other SQL expression.
Just remember:
- use
IS NULL - not
= NULL
That is a common beginner mistake.
CASE WHEN without ELSE
The ELSE part is optional.
Example:
SELECT
product_name,
stock_quantity,
CASE
WHEN stock_quantity < 10 THEN 'Low Stock'
END AS stock_warning
FROM products;
If the condition is not true and there is no ELSE, the result is NULL.
That can be useful, but it can also be confusing if you forget it.
For clarity, many developers prefer including ELSE explicitly:
CASE
WHEN stock_quantity < 10 THEN 'Low Stock'
ELSE 'OK'
END
This makes the result easier to interpret.
CASE WHEN in ORDER BY
CASE is very useful in ORDER BY when you want custom sorting rules.
Example:
SELECT
ticket_id,
priority
FROM support_tickets
ORDER BY
CASE
WHEN priority = 'Critical' THEN 1
WHEN priority = 'High' THEN 2
WHEN priority = 'Medium' THEN 3
ELSE 4
END;
This forces a custom order:
- Critical
- High
- Medium
- everything else
Without CASE, alphabetical ordering might not match the business priority.
This is one of the most practical CASE uses in operational systems.
CASE WHEN in GROUP BY reporting
CASE is often used to create categories before grouping.
Example:
SELECT
CASE
WHEN order_total >= 1000 THEN 'High Value'
WHEN order_total >= 500 THEN 'Medium Value'
ELSE 'Low Value'
END AS order_band,
COUNT(*) AS order_count
FROM orders
GROUP BY
CASE
WHEN order_total >= 1000 THEN 'High Value'
WHEN order_total >= 500 THEN 'Medium Value'
ELSE 'Low Value'
END;
This query:
- turns raw order totals into labels
- then counts how many orders fall into each label
That is a very common reporting pattern.
You are using CASE to transform raw values into categories that are easier to summarize.
CASE WHEN with aggregate functions
This is one of the most important uses of CASE.
You can combine CASE with aggregates like:
SUMCOUNTAVG
to do conditional aggregation.
This is extremely useful in reporting.
Example: count paid and unpaid orders
SELECT
SUM(CASE WHEN status = 'Paid' THEN 1 ELSE 0 END) AS paid_orders,
SUM(CASE WHEN status = 'Unpaid' THEN 1 ELSE 0 END) AS unpaid_orders
FROM orders;
This works because:
- each row becomes either 1 or 0
SUMadds them up
That gives conditional counts.
This pattern is everywhere in SQL reporting.
Example: total revenue for paid orders only
SELECT
SUM(CASE WHEN status = 'Paid' THEN order_total ELSE 0 END) AS paid_revenue
FROM orders;
This means:
- if the order is paid, add its total
- otherwise add zero
That gives you revenue only from paid orders, all in one query.
Example: average score only for passed students
SELECT
AVG(CASE WHEN score >= 50 THEN score END) AS average_passing_score
FROM exam_results;
Because there is no ELSE, non-matching rows return NULL.
And aggregate functions like AVG ignore NULL.
So this gives the average score only for passing students.
That is a very useful trick.
CASE WHEN versus WHERE
Beginners sometimes confuse CASE with WHERE.
WHERE
Filters rows out entirely.
CASE
Keeps the rows, but changes what value is returned for each row.
Example with WHERE:
SELECT *
FROM orders
WHERE status = 'Paid';
This removes unpaid rows.
Example with CASE:
SELECT
order_id,
CASE
WHEN status = 'Paid' THEN 'Included'
ELSE 'Excluded'
END AS status_flag
FROM orders;
This keeps all rows, but labels them differently.
That is an important distinction.
Use WHERE when you want to remove rows from the result. Use CASE when you want to classify or transform rows inside the result.
CASE WHEN in UPDATE statements
CASE is also very useful in UPDATE.
It lets you update rows differently based on conditions.
Example:
UPDATE employees
SET salary_band =
CASE
WHEN salary >= 100000 THEN 'High'
WHEN salary >= 60000 THEN 'Medium'
ELSE 'Low'
END;
This updates every row in the table, assigning a band based on salary.
That is much cleaner than running multiple separate updates in many cases.
Example: adjust discount by customer tier
UPDATE customers
SET discount_rate =
CASE
WHEN total_spend >= 5000 THEN 0.15
WHEN total_spend >= 2000 THEN 0.10
ELSE 0.05
END;
This is a classic use of CASE in data updates.
It helps translate business rules into one SQL statement.
CASE WHEN in INSERT or derived values
CASE can also be used in insert-select patterns or derived transformations.
Example:
INSERT INTO customer_segments (customer_id, segment_name)
SELECT
customer_id,
CASE
WHEN total_spend >= 5000 THEN 'VIP'
WHEN total_spend >= 1000 THEN 'Regular'
ELSE 'Basic'
END
FROM customers;
This is useful when generating derived reporting or classification tables.
CASE WHEN with dates
Date-based logic is another very common use case.
Example:
SELECT
order_id,
order_date,
CASE
WHEN order_date >= CURRENT_DATE - INTERVAL '7 days' THEN 'Last 7 Days'
WHEN order_date >= CURRENT_DATE - INTERVAL '30 days' THEN 'Last 30 Days'
ELSE 'Older'
END AS order_age_group
FROM orders;
This kind of logic is common in:
- dashboards
- aging reports
- retention analysis
- financial reporting
- operational monitoring
CASE helps turn raw dates into business-friendly categories.
CASE WHEN for bucketing values
One of the best use cases for CASE is bucketing.
Bucketing means converting continuous values into labeled ranges.
Examples:
- age bands
- salary ranges
- order value ranges
- score bands
- stock levels
- response time groups
Example:
SELECT
product_name,
price,
CASE
WHEN price < 50 THEN 'Budget'
WHEN price < 200 THEN 'Mid Range'
ELSE 'Premium'
END AS price_category
FROM products;
This is much more useful in reporting than looking at raw numbers alone.
CASE WHEN and boolean-style flags
CASE is very useful when you want readable yes/no style flags.
Example:
SELECT
customer_id,
total_spend,
CASE
WHEN total_spend >= 1000 THEN 'Yes'
ELSE 'No'
END AS is_high_value
FROM customers;
This is a very common pattern in business reporting and export queries.
CASE WHEN inside SUM for dashboard metrics
This deserves extra attention because it is one of the most important advanced beginner patterns.
Example:
SELECT
COUNT(*) AS total_orders,
SUM(CASE WHEN status = 'Paid' THEN 1 ELSE 0 END) AS paid_orders,
SUM(CASE WHEN status = 'Refunded' THEN 1 ELSE 0 END) AS refunded_orders,
SUM(CASE WHEN status = 'Paid' THEN order_total ELSE 0 END) AS paid_revenue
FROM orders;
This one query can power multiple dashboard metrics at once.
That is why CASE plus aggregate functions is such a powerful combination.
It lets you calculate many categorized summaries in one grouped or ungrouped result.
Common mistakes with CASE WHEN
There are a few mistakes that cause most CASE problems.
1. Wrong condition order
As mentioned earlier, CASE stops at the first match.
Bad:
CASE
WHEN score >= 50 THEN 'Pass'
WHEN score >= 80 THEN 'Excellent'
ELSE 'Fail'
END
Correct:
CASE
WHEN score >= 80 THEN 'Excellent'
WHEN score >= 50 THEN 'Pass'
ELSE 'Fail'
END
2. Forgetting ELSE
If no condition matches and there is no ELSE, SQL returns NULL.
That may be fine, but it often surprises people.
3. Mixing incompatible return types
All CASE result branches should usually return compatible types.
This is bad design:
CASE
WHEN score >= 50 THEN 'Pass'
ELSE 0
END
You are mixing:
- text
- and numeric output
Different databases handle this differently, but it is best to keep return types consistent.
4. Using CASE when a simple condition is clearer
Sometimes CASE works, but direct boolean logic is simpler.
For example, this:
WHERE CASE WHEN status = 'Paid' THEN 1 ELSE 0 END = 1
is much less clear than:
WHERE status = 'Paid'
CASE is powerful, but do not use it where normal SQL conditions are cleaner.
5. Repeating large CASE expressions everywhere
If the same CASE logic appears over and over, consider:
- a view
- a CTE
- a derived column in a query
- or a standardized reporting layer
Repeated logic is harder to maintain.
A practical mental model
The easiest way to think about CASE is this:
CASE creates a new value based on rules.
That value can then be used in:
SELECTORDER BYGROUP BY- aggregates
UPDATE- and sometimes
WHERE
So when you face a problem like:
- “I need different output depending on conditions”
CASE is usually the tool to consider first.
A practical workflow for writing CASE
When building a CASE expression, this workflow helps:
Step 1
Decide what output you want.
Example:
- status label
- band
- category
- flag
- custom sort rank
Step 2
List the business rules in order.
Example:
- if score is 80 or more, return Excellent
- if score is 50 or more, return Pass
- otherwise return Fail
Step 3
Write the CASE from most specific or highest threshold to lowest.
Step 4
Add ELSE explicitly unless you truly want NULL.
Step 5
Test a few sample rows mentally or with a small query.
This process catches a lot of CASE mistakes before they reach production.
Real-world examples of CASE WHEN usage
To show how practical CASE really is, here are common real-world uses.
Ecommerce
- classify customers by spend
- count paid versus refunded orders
- label high-value products
- sort orders by business priority
SaaS
- bucket accounts by plan usage
- label active versus inactive tenants
- measure trial versus paid accounts
- categorize support severity
Operations
- mark overdue tasks
- classify stock levels
- rank urgent work items
- label SLA breaches
Analytics
- create score bands
- build segment labels
- conditionally count events
- derive reporting categories
This is why CASE is one of the most useful SQL tools after joins and aggregates.
FAQ
What does CASE WHEN do in SQL?
CASE WHEN adds conditional logic to a SQL query. It lets you return different values depending on whether one or more conditions are true.
What is the difference between simple CASE and searched CASE in SQL?
Simple CASE compares one expression against multiple possible values, while searched CASE evaluates full boolean conditions such as greater than, less than, and combined logical checks.
Can you use CASE WHEN in a WHERE clause?
Yes, but it is often clearer to write the condition directly in WHERE when possible. CASE WHEN is more commonly used in SELECT, ORDER BY, GROUP BY, aggregates, and UPDATE statements.
Does SQL CASE WHEN stop at the first match?
Yes. CASE WHEN evaluates conditions in order and returns the result for the first matching condition, then stops checking the rest.
Final thoughts
SQL CASE WHEN is one of the most useful SQL features because it adds logic directly into your queries.
It helps you:
- label rows
- classify values
- build categories
- create dashboard metrics
- sort with business rules
- and update data conditionally
The most important things to remember are:
- CASE checks conditions in order
- it stops at the first match
ELSEmatters- it works especially well in reporting and aggregation
- and the real value comes from using it to express business logic clearly
If you understand CASE well, your SQL becomes much more expressive and much more useful in real-world reporting and application work.