CASE: Logic Directly in SELECT
If — then
A good archivist does more than read data — they label it.
The old Kotomarket archive contains raw facts:
- product price;
- order status;
- quantity in stock;
- user's city;
- event date.
But people often need a clear label alongside the raw fact.
For example, the products table contains prices:
| name | price |
|---|---|
| 1000-Piece Puzzle | $8.90 |
| Practical Algorithms | $16.90 |
| Slim Jeans | $39.90 |
The price itself is useful, but a report may be easier to read if it also shows a segment:
| name | price | segment |
|---|---|---|
| 1000-Piece Puzzle | $8.90 | cheap |
| Practical Algorithms | $16.90 | mid-range |
| Slim Jeans | $39.90 | mid-range |
CASE can add that label.
CASE is a branching expression:
CASE
WHEN condition1 THEN value1
WHEN condition2 THEN value2
ELSE default_value
END
You can read it almost like a set of instructions:
if condition 1 is true — return value 1;
otherwise, if condition 2 is true — return value 2;
otherwise, return the default value.
For example:
SELECT
name,
price,
CASE
WHEN price < 15 THEN 'cheap'
WHEN price < 40 THEN 'mid-range'
ELSE 'expensive'
END AS segment
FROM products;
Here, CASE creates a new calculated column called segment.
It doesn't change the data stored in the table.
It only adds a label to the query result.
QUERY: A label is the archivist's interpretation written over the facts. Choose your labels so they still make sense a hundred years from now.

CASE is the archivist's labeling tool: each row gets the label from the first matching condition.CASE checks branches from top to bottom: each row gets the value from the first matching WHEN, while everything else falls through to ELSE.products where category is Electronics, return name, stock, and a stock_label: fewer than 60 units — low, 60 to 99 — normal, and 100 or more — high.
In the SELECT list, CASE … END AS stock_label is the third column. You need a comma before it, after stock — just like between regular columns.CASE checks branches from top to bottom
The most important thing to remember about CASE is this:
the first matching WHEN wins.
As soon as SQL finds a branch whose condition returns TRUE, it takes the value after THEN and stops checking the remaining branches.
Consider this example:
CASE
WHEN price < 40 THEN 'not expensive'
WHEN price < 15 THEN 'cheap'
ELSE 'expensive'
END
At first glance, you might expect a $9.00 product to get the 'cheap' label.
But it won't.
Why?
For a price of $9.00, the first condition is already true:
price < 40
So CASE immediately returns:
not expensive
and this branch:
WHEN price < 15 THEN 'cheap'
is never reached.
So branch order is part of the logic, not just formatting.
For ranges, you usually put the narrower condition before the broader one:
CASE
WHEN price < 15 THEN 'cheap'
WHEN price < 40 THEN 'mid-range'
ELSE 'expensive'
END
With this order, a $9.00 product goes into the first branch, while a $25.00 product goes into the second.
What ELSE does
ELSE is the fallback.
It is used when none of the WHEN branches match.
For example:
CASE
WHEN price < 15 THEN 'cheap'
WHEN price < 40 THEN 'mid-range'
ELSE 'expensive'
END
If the price is $72.00, neither of the first two conditions matches:
72 < 15 -- no
72 < 40 -- no
So the expression returns the value from ELSE:
expensive
What happens if you leave out ELSE?
CASE
WHEN price < 15 THEN 'cheap'
WHEN price < 40 THEN 'mid-range'
END
If the price is $72.00, no WHEN matches. There is no fallback.
In that situation, CASE returns NULL.
In other words:
if no branch matches and there is no
ELSE, the result isNULL.
For reports, an explicit ELSE often makes the result clearer to the reader:
ELSE 'no segment'
or:
ELSE 'expensive'
The right choice depends on the business logic.
CASE is an expression, not a separate command
CASE returns a value.
That means you can use it anywhere SQL expects a value:
- in
SELECT; - in
ORDER BY; - sometimes in
WHERE; - inside calculations;
- inside in later modules.
In this lesson, we'll mainly use it in SELECT.
SELECT
name,
price,
CASE
WHEN price < 15 THEN 'cheap'
WHEN price < 40 THEN 'mid-range'
ELSE 'expensive'
END AS segment
FROM products;
Here, CASE acts as a calculated column.
You can think of it like this:
for each row, calculate a new value based on the conditions
Each row gets its own result.
A $9.00 product gets 'cheap'.
A $25.00 product gets 'mid-range'.
A $72.00 product gets 'expensive'.
CASE doesn't filter rows by itself. It works differently from WHERE.
WHERE decides:
keep this row or remove it?
CASE decides:
what value should we show for this row?
CASE for business-friendly labels
CASE is often used to turn technical values into labels that are easier for people to understand.
For example, the orders table contains statuses:
| id | status |
|---|---|
| 1 | paid |
| 2 | paid |
| 3 | cancelled |
| 4 | paid |
These values work well in the database: they're short, stable, and in English.
A report, however, can show more descriptive labels:
SELECT
id,
status,
CASE
WHEN status = 'paid' THEN 'Payment received'
WHEN status = 'pending' THEN 'Awaiting payment'
WHEN status = 'cancelled' THEN 'Order cancelled'
WHEN status = 'refunded' THEN 'Money refunded'
ELSE 'Unknown status'
END AS status_label
FROM orders;
Result:
| id | status | status_label |
|---|---|---|
| 1 | paid | Payment received |
| 2 | paid | Payment received |
| 3 | cancelled | Order cancelled |
| 4 | paid | Payment received |
This query doesn't change status in the table.
It simply adds a readable label beside it.
This is useful in reports, exports, , and practice tasks where the output should be easy for a person to read.
Searched CASE
The form we've used so far is called the searched form:
CASE
WHEN condition1 THEN value1
WHEN condition2 THEN value2
ELSE default_value
END
It's called searched CASE.
After each WHEN, you can write a complete condition:
WHEN price < 15 THEN 'cheap'
WHEN status = 'paid' THEN 'Payment received'
WHEN stock = 0 THEN 'out of stock'
WHEN price < 15 AND stock > 0 THEN 'cheap and in stock'
Searched CASE is flexible. You can:
- compare different columns;
- use
ANDandOR; - check for
NULLwithIS NULL; - define ranges;
- describe complex business rules.
For example:
SELECT
name,
price,
stock,
CASE
WHEN stock = 0 THEN 'out of stock'
WHEN price < 15 AND stock > 0 THEN 'cheap item in stock'
WHEN price >= 15 AND stock > 0 THEN 'item in stock'
ELSE 'check data'
END AS product_note
FROM products;
Here, each branch has its own condition.
Searched CASE is often easier for beginners because the conditions are written out explicitly.
Simple CASE
CASE has a second form: simple CASE.
It's useful when you compare the same column with several exact values.
For example, instead of writing this:
CASE
WHEN status = 'paid' THEN 'Payment received'
WHEN status = 'pending' THEN 'Awaiting payment'
WHEN status = 'cancelled' THEN 'Order cancelled'
WHEN status = 'refunded' THEN 'Money refunded'
ELSE 'Other status'
END
you can write a shorter version:
CASE status
WHEN 'paid' THEN 'Payment received'
WHEN 'pending' THEN 'Awaiting payment'
WHEN 'cancelled' THEN 'Order cancelled'
WHEN 'refunded' THEN 'Money refunded'
ELSE 'Other status'
END
Here, the expression status is written once:
CASE status
Then you list the values to compare it with:
WHEN 'paid' THEN 'Payment received'
WHEN 'pending' THEN 'Awaiting payment'
Simple CASE reads like a lookup table:
| status | status_label |
|---|---|
| paid | Payment received |
| pending | Awaiting payment |
| cancelled | Order cancelled |
| refunded | Money refunded |
It works well for straightforward mappings:
if the value equals this — show this label.
Simple vs. searched CASE: what's the difference?
Compare the two forms side by side.
Searched form:
CASE
WHEN status = 'paid' THEN 'Payment received'
WHEN status = 'pending' THEN 'Awaiting payment'
ELSE 'Other status'
END
Simple form:
CASE status
WHEN 'paid' THEN 'Payment received'
WHEN 'pending' THEN 'Awaiting payment'
ELSE 'Other status'
END
They can produce the same result.
But the logic is written differently.
In the simple form, SQL compares the expression after CASE with each value after WHEN:
status = 'paid'
status = 'pending'
In the searched form, you write each complete condition yourself:
WHEN status = 'paid'
WHEN status = 'pending'
The simple form is shorter when all the comparisons follow the same pattern.
The searched form is more flexible when the conditions differ.
For example, simple CASE can't express this logic cleanly:
CASE
WHEN status IS NULL THEN 'Status not specified'
WHEN status = 'paid' AND total_amount > 0 THEN 'Payment received'
WHEN status = 'pending' THEN 'Awaiting payment'
ELSE 'check order'
END
Here, we check NULL, inspect another column, total_amount, and use a compound condition with AND.
For cases like this, use the searched form.
A practical rule:
If you need to match one column against a set of exact values, you can use simple CASE.
If you need conditions, ranges, NULL, multiple columns, or AND/OR, use searched CASE.
Why WHEN NULL doesn't work in simple CASE
Simple CASE has an important pitfall.
Suppose orders.status can sometimes be NULL.
A beginner might write this:
CASE status
WHEN 'paid' THEN 'Payment received'
WHEN NULL THEN 'Status not specified'
ELSE 'Other status'
END
It may look as though this branch:
WHEN NULL THEN 'Status not specified'
should run when status is NULL.
But it never will.
Why?
Simple CASE status WHEN ... compares status with each branch value using ordinary equality, =.
So WHEN NULL effectively becomes:
status = NULL
From the lesson on NULL, you already know that:
status = NULL
doesn't return TRUE.
It returns UNKNOWN.
A WHEN branch runs only when its condition returns TRUE.
To check for NULL, use the searched form:
CASE
WHEN status IS NULL THEN 'Status not specified'
WHEN status = 'paid' THEN 'Payment received'
WHEN status = 'pending' THEN 'Awaiting payment'
ELSE 'Other status'
END
Here, the check is written correctly:
status IS NULL
The main rule:
check
NULLinCASEwithIS NULL, which means using the searched form.
THEN and ELSE values should be compatible
CASE returns one value.
Different branches, however, can return different possible values.
For example:
CASE
WHEN price < 15 THEN 'cheap'
WHEN price < 40 THEN 'mid-range'
ELSE 'expensive'
END
Every branch returns text. That's fine.
'cheap'
'mid-range'
'expensive'
But this CASE is suspicious:
CASE
WHEN price < 15 THEN 'cheap'
ELSE 0
END
One branch returns text:
'cheap'
The other returns a number:
0
The database has to determine the type of the CASE result: text or numeric. Depending on the situation, this may cause an error or an unexpected type conversion.
A good habit is:
THENandELSEbranches should return values of one clear, compatible type.
If you're creating a text label, return text from every branch:
CASE
WHEN price < 15 THEN 'cheap'
ELSE 'not cheap'
END
If you're creating a numeric rank, return numbers from every branch:
CASE
WHEN status = 'paid' THEN 1
WHEN status = 'pending' THEN 2
ELSE 3
END
This is especially important in ORDER BY, where CASE often returns a numeric priority.
CASE in ORDER BY: sorting by business order
Sometimes the default sort order isn't what you need.
For example, suppose you have these order statuses:
paid
pending
cancelled
refunded
If you sort them alphabetically:
SELECT id, status
FROM orders
ORDER BY status;
you get a text-based order.
But the business may want a different order:
- paid first;
- then pending;
- then cancelled;
- then refunded;
- then everything else.
Alphabetical order doesn't reflect that meaning. You can define the required order with CASE:
SELECT id, status
FROM orders
ORDER BY
CASE status
WHEN 'paid' THEN 1
WHEN 'pending' THEN 2
WHEN 'cancelled' THEN 3
WHEN 'refunded' THEN 4
ELSE 5
END,
id;
Here, CASE returns a numeric priority:
| status | priority |
|---|---|
| paid | 1 |
| pending | 2 |
| cancelled | 3 |
| refunded | 4 |
| other | 5 |
ORDER BY sorts by that priority.
The id at the end gives rows with the same status a consistent order:
ORDER BY CASE ... END, id
Rows with the same status are then sorted by id instead of appearing in an undefined order.
user_id = 2 as a funnel: return id and event_type from events. All view events should come first, followed by cart and then purchase, with rows sorted by id within each type.You can show a label and sort by the same logic
Sometimes it's useful to do both at once:
- show the reader a clear label;
- sort the rows by business order.
For example:
SELECT
id,
status,
CASE status
WHEN 'paid' THEN 'Payment received'
WHEN 'pending' THEN 'Awaiting payment'
WHEN 'cancelled' THEN 'Order cancelled'
WHEN 'refunded' THEN 'Money refunded'
ELSE 'Other status'
END AS status_label
FROM orders
ORDER BY
CASE status
WHEN 'paid' THEN 1
WHEN 'pending' THEN 2
WHEN 'cancelled' THEN 3
WHEN 'refunded' THEN 4
ELSE 5
END,
id;
In SELECT, CASE creates a text label:
status_label
In ORDER BY, another CASE creates a numeric sort priority.
Why not sort by the text label itself?
Because alphabetical order may still differ from the business order you need.
For example, it's better to define the order of 'Money refunded' and 'Payment received' explicitly because the required business order may differ from alphabetical order.
Use text for display and a numeric rank for ordering.
The key CASE rule
CASE checks branches from top to bottom and returns the result of the first WHEN that evaluates to TRUE.
CASE
WHEN price < 15 THEN 'cheap'
WHEN price < 40 THEN 'mid-range'
ELSE 'expensive'
END
The order of the conditions matters.
If no WHEN matches and there is no ELSE, the result is NULL.
To check for NULL, use the searched form:
CASE
WHEN status IS NULL THEN 'status not specified'
ELSE 'status is set'
END
Don't use WHEN NULL in the simple form.
Interview question
Interview question:
What does CASE do in SQL?
Strong answer:
CASE is a branching expression. It checks conditions and returns the value from the first matching branch. It's often used in SELECT to add readable labels to the result, such as a price segment or a status description. CASE doesn't change data in the table; it calculates a value for the query result.
Interview question:
In what order are WHEN branches checked?
Strong answer:
Branches are checked from top to bottom. The first WHEN whose condition returns TRUE is used, and the remaining branches aren't checked. So the order of conditions in CASE is part of the logic, not just formatting.
Interview question:
What does CASE return if no WHEN matches and there is no ELSE?
Strong answer:
It returns NULL. If a report needs a clear fallback value, it's better to add an explicit ELSE, such as ELSE 'Other status' or ELSE 'no segment'.
Interview question:
What's the difference between simple CASE and the searched form?
Strong answer:
Simple CASE is written as CASE x WHEN a THEN ... WHEN b THEN ... END and compares one expression, x, with the branch values using =. Searched CASE is written as CASE WHEN condition THEN ... END, and each branch can contain a complete condition: comparisons, ranges, AND/OR, IS NULL, and checks involving different columns.
Interview question:
Why does WHEN NULL never match in simple CASE?
Strong answer:
Because simple CASE compares its expression with branch values using =. A WHEN NULL branch effectively becomes x = NULL, and that comparison returns UNKNOWN rather than TRUE. A WHEN branch runs only for TRUE. To check NULL, use the searched form: WHEN x IS NULL THEN ....
Interview question:
Why use CASE in ORDER BY?
Strong answer:
Use CASE in ORDER BY when you need a business-defined order rather than alphabetical or numeric order. For example, statuses can be sorted as paid first, then pending, then cancelled, then refunded. Assign each status a numeric priority with CASE and sort by that value.
CASE return if no WHEN matches and there is no ELSE?CASE?
CASE
WHEN price < 40 THEN 'not expensive'
WHEN price < 15 THEN 'cheap'
ELSE 'expensive'
END
If price = 9.NULL correctly?CASE to sort statuses in business order?QUERY:
CASEis more than “if — then.” It's a way to tell the archive how a person should interpret raw facts.
- Wi-Fi Availability in CabinsEASY
- Calculate Special Employee BonusesEASY
- OTP Code Category IndicatorEASY
SELECT name, price, CASE WHEN price < 15 THEN 'cheap' WHEN price < 40 THEN 'mid-range' ELSE 'expensive' END AS segment FROM products ORDER BY price;