Chapter 13 · Lesson 1 of 4
CASE WHEN Basics
Use a searched CASE WHEN expression to label each row, such as sorting orders into small, medium, and large buckets based on their amount.
CASE is SQL's if/else. It checks conditions and returns a value for each row, so you can add a new label column without changing the table.
The most common form is the searched CASE: a list of WHEN condition THEN value branches, an optional ELSE, and END.
SELECT
order_id,
amount,
CASE
WHEN amount < 50 THEN 'small'
WHEN amount < 200 THEN 'medium'
ELSE 'large'
END AS size_band
FROM shop_orders
WHERE amount IS NOT NULLEach CASE expression produces one value per row. Give it an alias with AS so the result column has a readable name.
The WHERE amount IS NOT NULL filter keeps the order without an amount out of this first example. The next lesson shows why missing values need special care inside CASE.
Sample data
This lesson loads the shop_orders table (10 rows, one missing amount) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for shop_orders
CREATE OR REPLACE TABLE shop_orders (
order_id INTEGER,
customer VARCHAR,
amount DECIMAL(10,2),
status VARCHAR,
country VARCHAR,
order_date DATE
);
INSERT INTO shop_orders VALUES
(1, 'Ava', 45.00, 'shipped', 'US', '2024-03-01'),
(2, 'Ben', 180.00, 'shipped', 'DE', '2024-03-02'),
(3, 'Cara', 95.50, 'pending', 'US', '2024-03-03'),
(4, 'Dan', 320.00, 'cancelled', 'FR', '2024-03-04'),
(5, 'Eli', 12.99, 'shipped', 'DE', '2024-03-05'),
(6, 'Fay', 150.00, 'pending', 'US', '2024-03-06'),
(7, 'Gus', 99.99, 'shipped', 'FR', '2024-03-07'),
(8, 'Hana', 510.00, 'shipped', 'US', '2024-03-08'),
(9, 'Ivo', 75.25, 'refunded', 'DE', '2024-03-09'),
(10, 'Jun', NULL, 'pending', 'US', '2024-03-10');Practice challenge
For orders that have an amount, return order_id, amount, and size_band: 'small' when amount is below 50, 'medium' when it is below 200, and 'large' otherwise. Order by order_id.
Hint: CASE WHEN amount < 50 THEN 'small' WHEN amount < 200 THEN 'medium' ELSE 'large' END AS size_band, plus WHERE amount IS NOT NULL.
Run your query in the editor and the lesson checks the result automatically.
Lessons in CASE WHEN Expressions
Add conditional logic to queries with CASE WHEN: label rows, bucket numbers, map codes to readable values, and count or sum only the rows that match.
Related guides
SQL CASE WHEN Explained: Conditional Logic, Buckets, and Conditional Aggregation
CASE WHEN is SQL's if/else. Use it to label rows, build ranges, translate codes, and turn one grouped query into a compact pivot-style report.
SQL Cheat Sheet for Data Analysis: Filter, Group, Join, Dates, and Ranking
One pattern per common analysis question, from previewing a new table to ranking rows inside groups, each linked to a lesson where you can practice it.