Full answer
Tables and rows used here:
sql
CREATE TABLE payments (id int, method text, status text, amount numeric(10,2));
INSERT INTO payments VALUES
(1, 'upi', 'paid', 499), (2, 'card', 'failed', 1200), (3, 'upi', 'paid', 150),
(4, 'card', 'paid', 2300), (5, 'upi', 'refunded', 499), (6, 'netbanking', 'paid', 800);sql
SELECT count(*) AS total, count(*) FILTER (WHERE status = 'paid') AS paid, sum(amount) FILTER (WHERE status = 'paid') AS paid_amount, avg(amount) FILTER (WHERE method = 'upi') AS avg_upi, array_agg(id ORDER BY id) FILTER (WHERE status <> 'paid') AS problem_ids FROM payments;Output:
text
total | paid | paid_amount | avg_upi | problem_ids
-------+------+-------------+----------------------+-------------
6 | 4 | 3749.00 | 382.6666666666666667 | {2,5}
(1 row)sql
SELECT method, count(*) FILTER (WHERE status = 'paid') AS paid, count(*) FILTER (WHERE status <> 'paid') AS other FROM payments GROUP BY method ORDER BY method;PostgreSQL returns:
text
method | paid | other
------------+------+-------
card | 1 | 1
netbanking | 1 | 0
upi | 2 | 1
(3 rows)The first query scans the table once and returns six payments, four paid, 3749.00 collected and an average UPI amount of 382.67 (shown with numeric's full scale), plus the ids of the two problem payments. The second combines FILTER with GROUP BY for a per-method breakdown. The equivalent sum(CASE WHEN status = 'paid' THEN amount END) works on every database, so it is the portable choice, but FILTER is easier to read and also applies to aggregates where a CASE trick is awkward.
sql
CREATE TABLE payments (id int, method text, status text, amount numeric(10,2));
INSERT INTO payments VALUES
(1, 'upi', 'paid', 499), (2, 'card', 'failed', 1200), (3, 'upi', 'paid', 150),
(4, 'card', 'paid', 2300), (5, 'upi', 'refunded', 499), (6, 'netbanking', 'paid', 800);
SELECT count(*) AS total, count(*) FILTER (WHERE status = 'paid') AS paid, sum(amount) FILTER (WHERE status = 'paid') AS paid_amount, avg(amount) FILTER (WHERE method = 'upi') AS avg_upi, array_agg(id ORDER BY id) FILTER (WHERE status <> 'paid') AS problem_ids FROM payments;
SELECT method, count(*) FILTER (WHERE status = 'paid') AS paid, count(*) FILTER (WHERE status <> 'paid') AS other FROM payments GROUP BY method ORDER BY method;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- FILTER restricts one aggregate
- Several conditional aggregates in one scan
- Works with any aggregate
- Combines with GROUP BY
- CASE inside the aggregate is the portable form
Common mistakes
- Running one query per condition
- Using WHERE, which filters rows for every aggregate
Follow-ups
- How would you pivot statuses into columns for each month?
- Does FILTER work with window functions?
Tips
- Contrast with WHERE