Sub topic 3
FILTER with DISTINCT, ORDER BY, string_agg and array_agg
This chapter assumes you know aggregate functions, GROUP BY, window functions with OVER, and how NULL behaves in SQL. It uses the orders table from the earlier chapters.
FILTER with DISTINCT, ORDER BY, string_agg and array_agg
FILTER goes after the closing parenthesis of the aggregate call. It works alongside DISTINCT and ORDER BY written inside the call.
SELECT
customer_id,
array_agg(id ORDER BY created_at) FILTER (WHERE status = 'refunded') AS refunded_order_ids,
string_agg(DISTINCT status, ', ') AS statuses_seen
FROM orders
GROUP BY customer_id;Customers with no refunds get NULL in refunded_order_ids, because array_agg returns NULL when no row passes the filter.
Filtered aggregates as window functions
An aggregate used with OVER accepts FILTER too. This query gives a running paid total for each customer:
SELECT
id,
customer_id,
created_at,
sum(amount) FILTER (WHERE status = 'paid')
OVER (PARTITION BY customer_id ORDER BY created_at) AS running_paid_total
FROM orders;Every order keeps its own output row. An unpaid row shows the total up to that point, not zero, because the window still includes earlier paid rows.
Combining FILTER with GROUPING SETS and ROLLUP
ROLLUP adds subtotal rows. FILTER still limits each aggregate in every grouping set.
SELECT
customer_id,
count(*) AS orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
GROUP BY ROLLUP (customer_id)
ORDER BY customer_id;The row with a NULL customer_id is the grand total across all customers.
Performance: one scan instead of many, and reading EXPLAIN
Several FILTER aggregates in one SELECT read the table once. Separate queries for each condition read it once per query. Compare the plans with:
EXPLAIN ANALYZE
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid,
count(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders;Look for one scan of orders under a single Aggregate node. The actual time and rows values show what the database did, not only what it planned.
The diagram below shows the single-pass flow.
Pitfalls and limits
- FILTER works only on aggregate functions. Using it on a plain function is a syntax error.
sumandavgreturn NULL for an empty set. Wrap them incoalescewhen you need 0.- A WHERE clause removes rows from the whole query. FILTER removes rows from one aggregate only.
- In a window frame, FILTER skips rows that fail the condition, but earlier rows in the frame still count.
Exercise
Write one query that returns, for each customer, the number of paid orders and the total amount of refunded orders. Use a single pass over orders.
Show answer
SELECT customerid, count(*) FILTER (WHERE status = 'paid') AS paidorders, sum(amount) FILTER (WHERE status = 'refunded') AS refundedamount FROM orders GROUP BY customerid;