Chapter 13 · Lesson 3 of 4
Simple CASE for Value Mapping
Map codes to readable labels with the simple CASE form, CASE column WHEN value THEN label, such as grouping order statuses into open and closed.
When every branch compares the same column to a fixed value, the simple CASE form is shorter:
SELECT
order_id,
status,
CASE status
WHEN 'shipped' THEN 'complete'
WHEN 'pending' THEN 'open'
ELSE 'closed'
END AS status_group
FROM shop_ordersCASE status WHEN 'shipped' means the same as CASE WHEN status = 'shipped'. Use the simple form for lookups like status codes, country codes, or yes/no flags.
Two limits to remember:
• The simple form can only test equality. For ranges such as amount < 100, use the searched form.
• CASE status WHEN NULL never matches, because NULL = NULL is not true. Use WHEN status IS NULL in a searched CASE instead.
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
Return order_id, status, and status_group: 'complete' for shipped orders, 'open' for pending orders, and 'closed' for everything else. Order by order_id.
Hint: CASE status WHEN 'shipped' THEN 'complete' WHEN 'pending' THEN 'open' ELSE 'closed' END AS status_group
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.