SQL CASE WHEN: Labeling Rows
CASE is SQL's if/else. Use it to bucket numbers into readable labels.
A raw number like
quantity_on_hand
is precise but not very readable in a report.
CASE
lets you translate values into friendly labels.
SQL checks each
WHEN
from top to bottom and stops at the first one that's true, so order matters.
Anything left over falls through to
ELSE.
select product_name,
price,
case
when price >= 30 then 'premium'
when price >= 15 then 'mid'
else 'budget'
end as price_band
from products Order conditions from specific to general
A
CASE
expression isn't just a list of labels; it is a decision tree. Put the most
specific condition first so it gets a chance to match before a broader rule
catches the row.
In this lesson,
quantity_on_hand = 0
belongs before
quantity_on_hand < reorder_level. If the low-stock rule came first, an out-of-stock product would be
labeled "low" instead of "out of stock."
Use CASE WHEN to label code values
CASE is also useful when a table stores short codes or business
terms and the report needs readable labels. Garden Shop's orders carry
coupon codes like SPRING10. Most orders have no coupon, and a
NULL matches none of the WHEN tests, so it falls
through to ELSE.
select order_id,
coupon_code,
case
when coupon_code = 'SPRING10' then 'Spring promotion'
when coupon_code = 'SUMMER15' then 'Summer promotion'
when coupon_code = 'WELCOME5' then 'New-customer welcome'
else 'No coupon'
end as coupon_label
from orders Schema · Garden Shop Table · products 9 columns · 24 rows
One row per product, with price, cost, and inventory levels.
For every product, add a stock_status column:
'out of stock' when nothing is on hand,
'low' when the quantity is below the reorder level, and
'healthy' otherwise. Show the lowest stock first, and break
ties by product name.
Run your query to inspect the result.
Expected answer
- Columns: product_name, quantity_on_hand, reorder_level, stock_status.
- Rows: 24 products.
- Hanging Basket (0 on hand) is 'out of stock'; Pothos 'Golden' (8 < 12) is 'low'.
Related
Searched and simple CASE patterns.
Searched and simple CASE, plus conditional aggregation.
Practice WITH clauses and step-by-step reports.
Avoid truncating fractional results.
WHERE is evaluated before SELECT aliases exist.
The WITH clause, chained steps, and CTE vs subquery.