Conditional Aggregation in SQL: CASE Inside Aggregates and FILTER
How to compute several conditional counts and totals in one pass with CASE inside COUNT and SUM, and with the standard FILTER clause: the ELSE 0 counting bug, percentages and shares, rows into columns, conditions on groups in HAVING, and what each database supports.
kvi5hnuCode Sprout team member13 min readOn this page
A report rarely wants just one total. It wants shipped orders, pending orders and cancelled orders side by side, or revenue split into fulfilled and outstanding, or the share of orders that shipped. WHERE can't do this, because it applies one condition to the whole query: once it removes the pending orders, they're gone for every column.
Conditional aggregation solves it. Instead of filtering rows out of the query, you filter them per aggregate: each aggregate sees only the rows that meet its own condition. There are two ways to write it: a CASE expression inside the aggregate, which works in every database, and the FILTER clause from the SQL standard, which is shorter but not supported everywhere.
This technique is one of the most useful in SQL. It's the basis of pivot reports (article 44), and it turns many problems that look like they need several queries or subqueries into one simple GROUP BY.
The idea: CASE inside the aggregate
Article 11 introduced CASE as an expression that returns a value per row. Put one inside an aggregate, and the aggregate works on the values that the CASE returns:
COUNT(CASE WHEN status = 'shipped' THEN 1 END)
For each row, the CASE returns 1 if the order is shipped. Otherwise no WHEN matches and there's no ELSE, so it returns NULL. COUNT skips NULLs (article 18), so it counts exactly the shipped rows. The value 1 isn't important: any non-null value would do, because COUNT only checks whether it's NULL.
Here are four ways to count shipped orders, and the common mistake:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Four ways to count shipped orders, and one way to get it wrong
SELECT COUNT(*) AS all_orders,
COUNT(CASE WHEN status = 'shipped' THEN 1 END) AS count_case,
SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS sum_case,
COUNT(*) FILTER (WHERE status = 'shipped') AS count_filter,
COUNT(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS wrong
FROM orders;
all_orders | count_case | sum_case | count_filter | wrong
------------+------------+----------+--------------+-------
6 | 3 | 3 | 3 | 6
(1 row)
COUNT(CASE WHEN ... THEN 1 END)counts the non-null results: 3.SUM(CASE WHEN ... THEN 1 ELSE 0 END)adds 1 for each match and 0 for the rest: also 3. Many people prefer this form because it reads as "add one per match".COUNT(*) FILTER (WHERE status = 'shipped')uses theFILTERclause, explained below: 3 again.COUNT(CASE WHEN ... THEN 1 ELSE 0 END)returns 6, the number of all orders. TheELSE 0gives every row a non-null value, andCOUNTcounts them all.

So there are two correct patterns, and each goes with its own aggregate:
Use
COUNTwith noELSE, orSUMwithELSE 0. NeverCOUNTwithELSE 0.
The FILTER clause
The SQL standard has a cleaner syntax for the same thing. Add FILTER (WHERE condition) after any aggregate call, and only the rows that meet the condition are passed to it:
COUNT(*) FILTER (WHERE status = 'shipped')
SUM(amount) FILTER (WHERE status = 'pending')
AVG(price) FILTER (WHERE category = 'tents')
FILTER has a few advantages over CASE:
- It says what it means: "count the rows where ...".
- It works with
COUNT(*), which has no argument to put aCASEin. - It can't fall into the
ELSE 0trap. - It works with any aggregate, including ordered ones like
STRING_AGG(name, ', ' ORDER BY name) FILTER (WHERE ...).
The drawback is support. PostgreSQL (since 9.4), SQLite (since 3.30) and DuckDB support FILTER. MySQL, MariaDB, SQL Server and Oracle don't. In those, use CASE. Because the two forms are equivalent, you can learn the idea once and switch spelling as needed:
With FILTER | Portable CASE version |
|---|---|
COUNT(*) FILTER (WHERE c) | COUNT(CASE WHEN c THEN 1 END) |
SUM(x) FILTER (WHERE c) | SUM(CASE WHEN c THEN x END) |
AVG(x) FILTER (WHERE c) | AVG(CASE WHEN c THEN x END) |
MIN(x) FILTER (WHERE c) | MIN(CASE WHEN c THEN x END) |
COUNT(DISTINCT x) FILTER (WHERE c) | COUNT(DISTINCT CASE WHEN c THEN x END) |
Notice that the CASE versions have no ELSE. Rows that don't match become NULL, and every aggregate skips NULLs, which is exactly what "only look at matching rows" means. SUM(CASE WHEN c THEN x ELSE 0 END) is a common variation that differs in one way: when no row matches, it returns 0 instead of NULL, as the next section explains.
Several conditional totals in one pass
The real benefit appears with GROUP BY and several conditions at once. Here's revenue per category, split by order status. The examples use the sales view from article 20, which has one row per order line with its category, its order's status and its amount:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
\pset null '(null)'
-- Several conditional totals per category, all from one pass over the rows
SELECT category,
SUM(amount) AS total,
SUM(CASE WHEN status IN ('shipped', 'delivered') THEN amount ELSE 0 END) AS fulfilled,
SUM(CASE WHEN status = 'cancelled' THEN amount END) AS cancelled,
SUM(amount) FILTER (WHERE status = 'pending') AS pending
FROM sales
GROUP BY category
ORDER BY category;
category | total | fulfilled | cancelled | pending
----------+--------+-----------+-----------+---------
clothing | 94.00 | 94.00 | (null) | (null)
lighting | 103.50 | 103.50 | (null) | (null)
packs | 143.95 | 89.95 | 54.00 | (null)
tents | 738.99 | 249.99 | (null) | 489.00
(4 rows)
All four totals come from one scan of the data, one group per category. Getting the same report without conditional aggregation would need a separate grouped query per status, joined back together on category, which is longer, slower and easy to get wrong.
Look at the NULLs. SUM(CASE WHEN status = 'cancelled' THEN amount END) has no ELSE, so for categories with no cancelled lines, the SUM sees only NULLs and returns NULL. The FILTER version behaves the same way for pending. The fulfilled column uses ELSE 0, so every category gets a number, even if it has no fulfilled lines.
Which is right depends on the report:
- NULL says "there were no matching rows", which is useful if you need to distinguish "no sales" from "sales totalling zero".
- 0 is usually what a person reading a report expects. Get it with
ELSE 0, or by wrapping the aggregate:COALESCE(SUM(amount) FILTER (WHERE status = 'cancelled'), 0).
COUNT never has this problem: it returns 0, not NULL, when nothing matches.
Turning rows into columns
Counting each status in its own column turns the status values, which are spread over rows, into columns:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- One column per status: rows turned into columns
SELECT category,
COUNT(*) FILTER (WHERE status = 'shipped') AS shipped,
COUNT(*) FILTER (WHERE status = 'delivered') AS delivered,
COUNT(*) FILTER (WHERE status = 'pending') AS pending,
COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelled,
COUNT(*) AS all_lines
FROM sales
GROUP BY category
ORDER BY category;
category | shipped | delivered | pending | cancelled | all_lines
----------+---------+-----------+---------+-----------+-----------
clothing | 2 | 1 | 0 | 0 | 3
lighting | 1 | 1 | 0 | 0 | 2
packs | 0 | 1 | 0 | 1 | 2
tents | 1 | 0 | 1 | 0 | 2
(4 rows)
This is a pivot: categories down the side, statuses across the top, counts in the cells. Conditional aggregation is the portable way to pivot in SQL. Some databases have a PIVOT operator, and PostgreSQL has a crosstab function in an extension, but they all need you to list the output columns in advance, just like this query. Article 44 covers pivoting in depth, including what to do when the list of values isn't known in advance.
A useful check on a pivot: the conditional columns should add up to the unconditional total when the conditions cover every case without overlapping. Here, shipped + delivered + pending + cancelled = all_lines in every row. If they don't add up, a status is missing from the list, or a condition overlaps another.
Percentages and shares
A share is a conditional count divided by a total count:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- What share of orders has shipped?
SELECT COUNT(*) FILTER (WHERE status = 'shipped') / COUNT(*) AS integer_division,
ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'shipped')
/ COUNT(*), 1) AS pct_shipped,
ROUND(AVG(CASE WHEN status = 'shipped' THEN 1.0 ELSE 0 END), 3) AS share_avg_case,
ROUND(AVG((status = 'shipped')::int), 3) AS share_avg_bool
FROM orders;
-- Per category: share of revenue that is still pending
SELECT category,
ROUND(100.0 * COALESCE(SUM(amount) FILTER (WHERE status = 'pending'), 0)
/ SUM(amount), 1) AS pct_pending
FROM sales
GROUP BY category
ORDER BY category;
integer_division | pct_shipped | share_avg_case | share_avg_bool
------------------+-------------+----------------+----------------
0 | 50.0 | 0.500 | 0.500
(1 row)
category | pct_pending
----------+-------------
clothing | 0.0
lighting | 0.0
packs | 0.0
tents | 66.2
(4 rows)
integer_divisionshows the classic mistake: both counts are integers, so 3 / 6 is 0 in PostgreSQL, SQL Server and SQLite. Article 18 explained why.pct_shippedmultiplies by100.0first, which turns the calculation into decimal arithmetic before the division happens: 50.0.share_avg_caseuses a neat trick: the average of a 1-or-0 column is the share of 1s.AVG(CASE WHEN status = 'shipped' THEN 1.0 ELSE 0 END)gives 0.5. HereELSE 0is required: without it,AVGwould skip the non-matching rows and return 1.share_avg_booldoes the same in PostgreSQL by casting the Boolean condition to an integer (true becomes 1, false becomes 0).
The second query computes a share per group: the percentage of each category's revenue that is still pending. COALESCE(..., 0) turns "no pending lines" into 0 so the division returns 0.0 rather than NULL. If the denominator could be 0, protect it with NULLIF(SUM(amount), 0), which turns a zero divisor into NULL and the result into NULL instead of a division-by-zero error.
In MySQL, a comparison returns 1 or 0, so SUM(status = 'shipped') counts matches and AVG(status = 'shipped') gives the share directly. It's concise but MySQL-specific. In SQL Server, IIF(condition, 1, 0) is a short form of the CASE.
Conditions on groups
Conditional aggregates also work in HAVING, where they answer questions about the mix of rows in each group. "Which customers have at least one fulfilled order and no pending or cancelled ones?" is two conditional counts:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Customers with at least one fulfilled order and no pending or cancelled ones
SELECT c.name,
COUNT(*) FILTER (WHERE o.status IN ('shipped', 'delivered')) AS fulfilled,
COUNT(*) FILTER (WHERE o.status IN ('pending', 'cancelled')) AS open_or_cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING COUNT(*) FILTER (WHERE o.status IN ('shipped', 'delivered')) > 0
AND COUNT(*) FILTER (WHERE o.status IN ('pending', 'cancelled')) = 0
ORDER BY c.name;
-- Conditional MIN and STRING_AGG: per customer, first shipped date and non-cancelled statuses
SELECT customer_id,
MIN(placed_on) FILTER (WHERE status = 'shipped') AS first_shipped,
STRING_AGG(status, ', ' ORDER BY placed_on)
FILTER (WHERE status <> 'cancelled') AS statuses,
COUNT(DISTINCT CASE WHEN status <> 'cancelled' THEN order_id END) AS live_orders
FROM orders
WHERE customer_id IS NOT NULL
GROUP BY customer_id
ORDER BY customer_id;
name | fulfilled | open_or_cancelled
------------+-----------+-------------------
Asha Rao | 2 | 0
Ben Okafor | 1 | 0
(2 rows)
customer_id | first_shipped | statuses | live_orders
-------------+---------------+--------------------+-------------
1 | 2026-03-02 | shipped, delivered | 2
2 | 2026-03-05 | shipped | 1
3 | (null) | pending | 1
4 | (null) | (null) | 0
(4 rows)
Asha and Ben qualify. Chen has a pending order, and Dana's only order was cancelled, so both fail the second condition. Questions shaped like "has some X and no Y" or "all of its rows are Z" are common, and this pattern handles them all:
- All rows match:
HAVING COUNT(*) FILTER (WHERE NOT condition) = 0, orHAVING COUNT(*) = COUNT(*) FILTER (WHERE condition). Watch out for NULLs here: a row where the condition is unknown is neither counted as matching nor as not matching. - At least one row matches:
HAVING COUNT(*) FILTER (WHERE condition) > 0. - No row matches:
HAVING COUNT(*) FILTER (WHERE condition) = 0.
The same questions can be written with EXISTS and NOT EXISTS (article 16). The grouped version is often simpler when you also want counts in the output, as here.
The second query shows that conditional aggregation works with every aggregate:
MIN(placed_on) FILTER (WHERE status = 'shipped')is each customer's first shipped order date. Customers with no shipped orders get NULL.STRING_AGG(...) FILTER (WHERE status <> 'cancelled')lists the statuses of the customer's orders, skipping cancelled ones. For Dana, every order was cancelled, so there's nothing to join, and the result is NULL.COUNT(DISTINCT CASE WHEN status <> 'cancelled' THEN order_id END)counts distinct live orders.
A trap with COUNT(DISTINCT ... ELSE ...)
With COUNT(DISTINCT ...), an ELSE value is counted as one extra distinct value. COUNT(DISTINCT CASE WHEN status <> 'cancelled' THEN order_id ELSE 0 END) would count the 0 as an order whenever any row in the group is cancelled. Leave the ELSE out, so non-matching rows become NULL and are skipped.
CASE in the aggregate or CASE in GROUP BY?
Both put a CASE in a grouped query, but they do different things:
CASEinGROUP BY(article 19) creates the rows of the result: one row per price band, per status, per period.CASEinside an aggregate creates columns: one column per condition, all computed for the same groups.
Many reports combine both. For example, group by month (rows) and count each status (columns).
What's current
FILTERhas been in the SQL standard since SQL, and is supported by PostgreSQL (9.4+), SQLite (3.30+) and DuckDB. MySQL, MariaDB, SQL Server and Oracle still don't support it, so theCASEform remains the portable choice.- PostgreSQL also allows
FILTERon aggregate functions used as window functions (Part 6), such asCOUNT(*) FILTER (WHERE status = 'shipped') OVER (...). - Conditional aggregation is how
PIVOT-style reports are written in databases that have noPIVOToperator, which includes PostgreSQL, MySQL and SQLite.
Common questions
Why does COUNT(CASE WHEN ... THEN 1 ELSE 0 END) count every row?
Because ELSE 0 gives every row a non-null value, and COUNT counts non-null values. Remove the ELSE, or change COUNT to SUM.
Should I use COUNT(CASE ...) or SUM(CASE ... ELSE 0 END)?
They give the same result whenever the group has rows. On empty input, SUM with ELSE 0 returns NULL and COUNT returns 0. Pick one style and use it consistently.
Is FILTER faster than CASE?
In PostgreSQL they perform about the same. FILTER is mainly clearer, and it lets you use COUNT(*).
Why is my conditional SUM NULL instead of 0?
No row in the group met the condition, so the SUM saw only NULLs. Add ELSE 0, or wrap it in COALESCE(..., 0).
Can I use conditional aggregates without GROUP BY?
Yes. Then they summarize the whole table in one row, as in the first example.
Can I put a subquery in the condition?
In FILTER (WHERE ...) and in CASE WHEN ..., yes, but a correlated subquery runs for each row, which can be slow. A join usually works better.
How do I calculate a percentage without getting 0?
Make the arithmetic decimal before dividing: 100.0 * COUNT(...) / COUNT(*), or use AVG of a 1.0-or-0 CASE.
What does a condition that evaluates to unknown do?
CASE WHEN treats unknown like false, and so does FILTER (WHERE ...). A row where the condition involves a NULL is not counted as matching. So "matching" plus "not matching" can be fewer than all rows if the column has NULLs. Use IS NULL or IS DISTINCT FROM in the condition when NULLs matter.
Summary
- Conditional aggregation applies a condition to each aggregate separately, so one query can return many conditional counts and totals from one pass over the data.
- The portable form puts a
CASEwith noELSEinside the aggregate. Non-matching rows become NULL and are skipped. COUNTwithELSE 0counts every row. UseCOUNTwithoutELSE, orSUMwithELSE 0.- The standard
FILTER (WHERE ...)clause does the same more clearly, in PostgreSQL, SQLite and DuckDB, but not MySQL, SQL Server or Oracle. - Conditional
SUM,AVG,MINandMAXreturn NULL when no rows match. UseCOALESCEwhen the report should show 0. - Shares are conditional counts divided by totals. Use decimal arithmetic, or
AVGof a 1-or-0 value. - One conditional column per value turns rows into columns, which is the portable way to pivot.
- In
HAVING, conditional counts answer "has some X", "has no Y" and "all rows are Z" questions about each group.
Practice questions
What does each of these return on the six orders (three shipped)? (a) COUNT(CASE WHEN status = 'shipped' THEN 'yes' END), (b) COUNT(CASE WHEN status = 'shipped' THEN 1 ELSE NULL END), (c) SUM(CASE WHEN status = 'shipped' THEN 1 END), (d) COUNT(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END).
Answer
(a) 3: the value doesn't matter, only whether it's NULL. (b) 3: ELSE NULL is the same as no ELSE. (c) 3: the SUM of three 1s, with the NULLs skipped. It would return NULL, not 0, if no order were shipped. (d) 6: every row gets a non-null value.
Write a query that returns, for each product category, the number of products, the number that are out of stock (stock = 0), and the number with no brand. It must work in MySQL as well as PostgreSQL.
Answer
SELECT category,
COUNT(*) AS products,
COUNT(CASE WHEN stock = 0 THEN 1 END) AS out_of_stock,
COUNT(CASE WHEN brand IS NULL THEN 1 END) AS no_brand
FROM products
GROUP BY category
ORDER BY category;
FILTER isn't available in MySQL, so the CASE form is needed. On the course data, packs has one out-of-stock product and lighting has one product with no brand. Note brand IS NULL rather than brand = NULL, which is never true.
Write a PostgreSQL query that returns the percentage of order lines (from order_items) whose qty is greater than 1, rounded to one decimal place.
Answer
SELECT ROUND(100.0 * COUNT(*) FILTER (WHERE qty > 1) / COUNT(*), 1) AS pct_multi
FROM order_items;
Three of the nine lines have a quantity above 1, so the result is 33.3. Multiplying by 100.0 before dividing avoids integer division.
Write a query that lists customers all of whose orders are shipped or delivered. Customers with no orders should not be listed.
Answer
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING COUNT(*) = COUNT(CASE WHEN o.status IN ('shipped', 'delivered') THEN 1 END);
A group qualifies when every one of its rows matches. The inner join leaves out customers with no orders. On the course data, Asha and Ben are listed.
A report uses AVG(CASE WHEN status = 'shipped' THEN 1.0 END) to get the share of shipped orders, and it always returns 1. Why?
Answer
Without ELSE 0, non-shipped rows give NULL, and AVG skips NULLs. It averages only the 1.0 values, so the result is 1 whenever any order is shipped. For a share, every row must contribute: AVG(CASE WHEN status = 'shipped' THEN 1.0 ELSE 0 END).
Previous: Subtotals and Grand Totals With ROLLUP, CUBE and GROUPING SETS

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.