1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL CASE WHEN Statement: Syntax, Real Examples and Common Mistakes

CASE WHEN is how you write if-then logic in SQL. Learn both forms, then use it for labels, pivot-style reports, custom sorting and safe updates, while avoiding the NULL and ordering traps.

8 min read
SQL CASE WHEN statement: syntax, real examples and common mistakes

Key takeaways

  • CASE returns a value based on the first condition that is true.
  • Put the most specific conditions first, or later ones may never be reached.
  • With no ELSE, unmatched rows return NULL.
  • Inside SUM or COUNT, CASE turns one query into a compact pivot-style report.

Most reports need some logic: label orders as large or small, count paid and pending orders side by side, or show urgent items first. SQL CASE WHEN handles all of this directly inside a query, and it works across all the major databases.

We ran every query here in SQLite 3.50, and the results shown come from that run. CASE is part of standard SQL, so it behaves the same way in PostgreSQL, MySQL, SQL Server and Oracle for these examples.

What is CASE WHEN?

CASE is an expression, not a separate command. It evaluates conditions in order and returns a value, so it can go anywhere a value is allowed: in SELECT, WHERE, GROUP BY, ORDER BY, or inside functions. It always ends with END.

CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ELSE fallback
END

The sample table

CREATE TABLE orders (id INT, customer TEXT, total INT, status TEXT);

INSERT INTO orders VALUES
 (1,'Asha',1200,'paid'), (2,'Ben',300,'pending'),
 (3,'Asha',800,'paid'), (4,'Chitra',2500,'shipped'),
 (5,'Dev',150,'cancelled'), (6,'Ben',NULL,'pending');

Notice that order 6 has no total. That row matters later on.

Searched CASE

This is the more flexible form, since each WHEN has a full condition of its own:

SELECT id, total,
       CASE
         WHEN total >= 1000 THEN 'large'
         WHEN total >= 500 THEN 'medium'
         ELSE 'small'
       END AS size
FROM orders;

-- 1 | 1200 | large
-- 2 |  300 | small
-- 3 |  800 | medium
-- 4 | 2500 | large
-- 5 |  150 | small
-- 6 | NULL | small

Look at the last row. Order 6 has no total, yet it is labelled “small”. Both comparisons with NULL were not true, so it fell through to ELSE. We show how to fix this in the NULL section. Always give the result a name using AS, or you may get an awkward column name.

Simple CASE

When you are comparing one column with fixed values, the shorter form reads better:

SELECT id,
       CASE status
         WHEN 'paid' THEN 'Complete'
         WHEN 'shipped' THEN 'Complete'
         WHEN 'pending' THEN 'Waiting'
       END AS label
FROM orders;

-- 1 | Complete
-- 2 | Waiting
-- 3 | Complete
-- 4 | Complete
-- 5 | NULL
-- 6 | Waiting
Form Compares Can use ranges? Best for
Simple One expression for equality No Mapping codes to labels
Searched Any condition per branch Yes Ranges, multiple columns, NULL checks

Order matters

CASE stops at the first true condition, and this is the most common logic bug. Swap the two conditions from our earlier query:

SELECT id, total,
       CASE
         WHEN total >= 500 THEN 'medium'
         WHEN total >= 1000 THEN 'large'
         ELSE 'small'
       END AS size
FROM orders WHERE id IN (1, 4);

-- 1 | 1200 | medium
-- 4 | 2500 | medium

Now nothing can ever be “large”. A total of 2500 is also at least 500, so the first branch wins and the second is never reached. No error appears, only wrong labels. For ranges, put the most restrictive condition first, or write complete ranges, such as total >= 500 AND total < 1000.

What happens with no ELSE?

In our simple CASE example above, order 5 was cancelled, and no branch handled that, so the result was NULL. Sometimes that is exactly what you want, as the next section shows. But when building labels, a clear ELSE 'other' is usually better, since it makes unexpected values visible rather than leaving blanks in a report.

Tip: All branches should return the same type. Mixing text and numbers works loosely in SQLite, but stricter databases, such as PostgreSQL, will raise an error, or try to convert values in ways you did not intend.

Pivot-style reports with SUM

This is one of the most useful patterns in everyday SQL. Wrapping CASE in an aggregate turns rows into columns, with one row per customer:

SELECT customer,
       SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END) AS paid,
       SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending_orders
FROM orders
GROUP BY customer
ORDER BY customer;

-- Asha   | 2000 | 0
-- Ben    |    0 | 2
-- Chitra |    0 | 0
-- Dev    |    0 | 0

One query now gives both paid revenue and the number of pending orders, with no need for separate queries or joins. The pattern works in nearly every database, unlike the dedicated PIVOT syntax that only some offer. If GROUP BY is new to you, read SQL GROUP BY and HAVING.

Conditional counts

COUNT skips NULLs, so a CASE with no ELSE counts only the rows that match:

SELECT COUNT(*) AS all_orders,
       COUNT(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
       COUNT(CASE WHEN total >= 1000 THEN 1 END) AS large_orders
FROM orders;

-- 6 | 2 | 2

Be careful: if you add ELSE 0 inside a COUNT, every row gets counted, because 0 is not NULL. Use ELSE 0 with SUM, and leave it out with COUNT. PostgreSQL and SQLite also support COUNT(*) FILTER (WHERE ...), which reads nicely, but it is not available everywhere.

Grouping by a CASE

You can create your own buckets, and then summarize them:

SELECT CASE WHEN total >= 1000 THEN 'large' ELSE 'other' END AS bucket,
       COUNT(*)
FROM orders
GROUP BY bucket
ORDER BY bucket;

-- large | 2
-- other | 4

Grouping by the alias works in SQLite, PostgreSQL and MySQL. SQL Server does not allow it, so you would have to repeat the whole expression, or put the query in a CTE or subquery first.

Custom sorting with ORDER BY

Alphabetical order is rarely what a business wants. CASE lets you define your own order:

SELECT id, status FROM orders
ORDER BY CASE status
           WHEN 'pending' THEN 1
           WHEN 'paid' THEN 2
           ELSE 3
         END, id;

-- 2 | pending
-- 6 | pending
-- 1 | paid
-- 3 | paid
-- 4 | shipped
-- 5 | cancelled

Pending orders come first, which is handy for a work queue. The second sort column, id, keeps the rows in a predictable order within each group.

CASE in UPDATE

CASE lets one statement apply different changes to different rows. Here, small pending orders are flagged for review:

UPDATE orders
SET status = CASE
               WHEN status = 'pending' AND total < 500 THEN 'review'
               ELSE status
             END;

SELECT id, status FROM orders WHERE customer = 'Ben';

-- 2 | review
-- 6 | pending

The ELSE status keeps other rows unchanged. Leaving it out is dangerous, because unmatched rows would be set to NULL. Without a WHERE clause this statement also touches every row, so on large tables add a filter, and consider wrapping the change in a transaction so that you can check the result before you commit. Notice too that order 6 did not change, because its NULL total did not satisfy total < 500.

NULL traps

NULL causes two separate problems with CASE. First, the simple form compares using equality, and nothing equals NULL, not even NULL itself:

SELECT CASE NULL WHEN NULL THEN 'matched' ELSE 'not matched' END;

-- not matched

So CASE col WHEN NULL never matches. Use the searched form with IS NULL instead. Second, as we saw with order 6, a NULL value slips past comparisons and lands in ELSE. The fix is to check for it first:

SELECT id,
       CASE
         WHEN total IS NULL THEN 'unknown'
         WHEN total >= 1000 THEN 'large'
         ELSE 'other'
       END AS size
FROM orders WHERE id IN (1, 2, 6);

-- 1 | large
-- 2 | other
-- 6 | unknown

Order 6 now gets an honest label. Our guide to SQL NULL values covers this behaviour in full.

CASE vs other options

Option Works in Use it when
CASE All major databases You want portable logic
COALESCE All major databases You only need a fallback for NULL
IF() MySQL A simple two-way choice
IIF() SQL Server, SQLite A simple two-way choice
DECODE() Oracle Older Oracle code
Lookup table All The mapping is long or changes often

That last option deserves a thought. If a CASE grows to thirty branches and appears in five queries, move the mapping into a table and join to it. Then a change is a single row update, rather than a code change in five places.

Common mistakes

  • Wrong condition order. A broad condition first hides the narrower ones.
  • Forgetting END. This is the most frequent syntax error.
  • Using WHEN NULL. It never matches, so use WHEN col IS NULL.
  • Adding ELSE 0 inside COUNT. It counts all rows.
  • Omitting ELSE in an UPDATE. It can wipe values with NULL.
  • Filtering by CASE in WHERE. It can stop an index from being used. See our guide to SQL query optimization.

Final thoughts

CASE WHEN is a small feature that does a great deal of work. Remember three rules: the first true branch wins, unmatched rows become NULL without an ELSE, and NULL needs its own check. To practise, take a report you currently build with several queries, and try to produce it as one query using SUM(CASE ...).

Frequently asked questions

What does CASE WHEN do in SQL?

It adds if-then logic to a query. SQL checks each condition in order and returns the value for the first one that is true, or the ELSE value if none is.

What happens if there is no ELSE in a CASE statement?

Rows that match no condition return NULL. This is useful inside COUNT, but in labels and updates it can cause blanks or lost data.

Can I use CASE in a WHERE clause?

Yes, because it is an expression. However, plain AND and OR conditions are usually clearer, and they are more likely to make use of an index.

What is the difference between simple and searched CASE?

Simple CASE compares one expression with fixed values for equality. Searched CASE has a full condition in each WHEN, so it can handle ranges and NULL checks.

Can CASE statements be nested?

Yes, a CASE can appear inside another. Deep nesting gets hard to read, though, so consider combining conditions with AND or using a lookup table.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →