SQL CASE WHEN: if-then-else logic inside a query

CASE WHEN lets a query decide what goes into a column: in stock or out of stock, budget or premium, done or still in progress. It is the IF of SQL, and you can use it anywhere a value is allowed.

In short: CASE WHEN stock = 0 THEN 'out of stock' ELSE 'in stock' END checks the condition for every row and returns the matching text. You can stack several WHEN branches; the first one that is true wins. Without ELSE you get NULL. END closes the expression.

What you should know first: conditions with WHERE and groups with GROUP BY.

Try it now

The products table stores stock as a number. On the phone, a plain label is far more useful.

Task Customer service wants to see at a glance what can ship. From the products table, show name and a column stock_status that says 'out of stock' when stock is 0 and 'in stock' otherwise, all in lower case.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

How CASE WHEN works

CASE is an expression, just like a calculation. It goes in the SELECT list, gets a name with AS, and produces one value per row. The conditions after WHEN decide which value. You write them exactly as you would in WHERE, with =, <, IN, LIKE, AND and OR.

SELECT order_id, status,
       CASE WHEN status IN ('delivered', 'cancelled') THEN 'closed'
            ELSE 'in progress'
       END AS stage
FROM orders
WHERE order_date >= '2026-05-01';
order_idstatusstage
1012deliveredclosed
1013cancelledclosed
1014shippedin progress
1015shippedin progress
1016openin progress
1017openin progress
1018openin progress

Nothing in the table changes. The stage column exists only in this result.

The short form for fixed values

When you compare one column against a list of fixed values, you can name the column once, right after CASE: CASE status WHEN 'open' THEN 'Needs action' WHEN 'shipped' THEN 'On its way' ELSE 'Done' END. That is the same as CASE WHEN status = 'open' THEN ..., only shorter. For <, > or LIKE you need the long form.

Several conditions: order matters

CASE reads the WHEN branches from top to bottom and takes the first one that is true. Once a row has matched, the remaining branches are skipped. So you line up your thresholds from low to high (or high to low) and let ELSE catch whatever is left. The next exercise shows why that matters.

Task For the new catalog, marketing sorts products into price bands: under 10 is 'budget', 10 to under 100 is 'standard', 100 and up is 'premium'. From the products table, show name, price and price_band.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

CASE in ORDER BY: a custom sort order

Alphabetically, cancelled would come before open. The warehouse wants open orders on top, then shipped ones, then everything else. CASE turns each status into a rank, and the query sorts by that rank:

SELECT order_id, order_date, status
FROM orders
WHERE order_date >= '2026-05-01'
ORDER BY CASE status WHEN 'open' THEN 1
                     WHEN 'shipped' THEN 2
                     ELSE 3
         END,
         order_date;
order_idorder_datestatus
10162026-06-12open
10172026-06-13open
10182026-06-14open
10142026-06-02shipped
10152026-06-10shipped
10122026-05-06delivered
10132026-05-19cancelled

The rank never shows up in the output; it only drives the sort.

CASE inside SUM: conditional counts

Wrap CASE in a sum and you count only the rows that meet a condition. Better still, you can count several conditions side by side in one row:

SELECT COUNT(*) AS orders,
       SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
       SUM(CASE WHEN status IN ('open', 'shipped') THEN 1 ELSE 0 END) AS in_progress,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;
ordersdeliveredin_progresscancelled
181152

With WHERE you would need three separate queries. Add GROUP BY and you get a cross-tab, much like a PivotTable in Excel: groups down the side, conditions across the top.

Task Purchasing wants to know, per category, how many products there are and how many of them are out of stock (stock 0). Show category, products (the number of all products) and out_of_stock (the number with stock 0). Every category must appear, even if nothing in it is sold out.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

CASE and IF in Excel

If you use Excel, you already know the idea. CASE WHEN price < 10 THEN 'budget' ELSE 'other' END does what =IF(B2<10,"budget","other") does, and several WHEN branches work like IFS or nested IF formulas. Two differences: in SQL you write the logic once for the whole column instead of filling it down, and a missing ELSE gives you NULL rather than FALSE.

Common mistakes

Forgetting END

Without END the database can't tell where CASE stops. If AS follows straight after, the exercise says Syntax error near "AS". Every CASE needs exactly one END.

Branches in the wrong order

Put WHEN price < 100 above WHEN price < 10 and the second branch can never fire. There is no error, just wrong labels, and the exercise tells you the columns and row count match but the values don't.

Leaving out ELSE

If no WHEN is true and there is no ELSE, the result is NULL. Laura Hughes has no salary on file, so neither salary >= 48000 nor salary < 48000 is true for her (see NULL). An ELSE branch catches rows like that.

A comma between branches

THEN 'budget', WHEN ... looks like a list, but it's a syntax error near ",". WHEN branches are separated by a space or a line break, never a comma.

COUNT instead of SUM for conditional counts

COUNT(CASE WHEN ... THEN 1 ELSE 0 END) counts every row, because 0 is still a value. Use SUM with ELSE 0, or COUNT with no ELSE at all, so that the non-matching rows become NULL and COUNT skips them.

CASE in MySQL, PostgreSQL, SQL Server and SQLite

Both forms of CASE WHEN are standard SQL and behave the same in all four databases; a missing ELSE gives NULL everywhere. For the simple "if, then, else" case, some of them add a shortcut:

DatabaseShortcutNote
MySQLIF(stock = 0, 'out of stock', 'in stock')returns the third value when the condition is false or NULL
PostgreSQLnonethe docs list CASE, COALESCE, NULLIF, GREATEST and LEAST as its conditional expressions
SQL ServerIIF(stock = 0, 'out of stock', 'in stock')Microsoft calls it a shorthand for CASE; CASE and IIF can be nested at most 10 levels deep
SQLite (these exercises)IIF(stock = 0, 'out of stock', 'in stock')per the docs it compiles to the same code as CASE. Here it takes exactly three values: the two-value form and the spelling IF() arrived in SQLite 3.48, more than three values in 3.49

The exercises in this lesson ask for CASE because it runs on every database, so an IIF answer gets "Solve this one with CASE".

Sources: MySQL Reference Manual (Flow Control Functions), PostgreSQL documentation (Conditional Expressions), Microsoft Learn (CASE, IIF), sqlite.org (Core Functions, SQL Language Expressions).

FAQ

Can I use CASE in WHERE?

Yes, CASE works anywhere a value is allowed. In WHERE it's rarely needed, though; AND and OR usually do the job and read more easily. The common spots are the SELECT list, ORDER BY and inside aggregates.

Can one CASE return numbers in some branches and text in others?

SQLite lets it slide. PostgreSQL and SQL Server need all THEN and ELSE values to fit one common data type, and raise an error otherwise. Keep each CASE to either text or numbers.

Can I group by a CASE column?

Yes. Put the same CASE expression after GROUP BY to count, say, how many products fall into each price band: 5 budget, 2 standard and 5 premium in the practice data. SQLite also accepts the AS name after GROUP BY. Not every database does, so repeating the full expression is the safe habit.

Is there a limit on the number of WHEN branches?

Use as many as you need. Once you pass five or so, a small lookup table with thresholds and labels, joined to your data, is often easier to maintain. Joins come in level 3.

Learn this next: string functions

Build full names, make short codes, strip dashes out of phone numbers: with ||, SUBSTR, REPLACE, UPPER and TRIM you get text into exactly the shape you need.

Practice string functions

Write to us

Choose language

Select your preferred language