Chapter 13 · Lesson 4 of 4
Conditional Aggregation
Put CASE inside COUNT and SUM to aggregate only matching rows, building pivot-style reports such as shipped orders and revenue per country.
CASE becomes even more useful inside aggregate functions. Instead of filtering the whole query with WHERE, you can count or sum only the rows that match a condition, while keeping every group.
SELECT
country,
COUNT(*) AS all_orders,
COUNT(CASE WHEN status = 'shipped' THEN 1 END) AS shipped_orders,
SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_amount
FROM shop_orders
GROUP BY countryHow it works:
• COUNT(CASE WHEN ... THEN 1 END) counts only matching rows, because COUNT ignores the NULL produced for non-matching rows.
• SUM(CASE WHEN ... THEN amount ELSE 0 END) adds the amount for matching rows and 0 for the rest.
This pattern is often called conditional aggregation. It turns rows into side-by-side columns, like a small pivot table.
DuckDB also supports the standard FILTER clause, which reads nicely for the same idea:
SELECT country, COUNT(*) FILTER (WHERE status = 'shipped') AS shipped_orders
FROM shop_orders
GROUP BY countrySample 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 each country, return country, shipped_orders (the number of shipped orders), and shipped_amount (the total amount of shipped orders). Order by country.
Hint: COUNT(CASE WHEN status = 'shipped' THEN 1 END) and SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END), grouped by country.
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.