Sub topic 8
FILTER with DISTINCT, ORDER BY, string_agg and array_agg
This chapter assumes you can write GROUP BY queries and know that FILTER (WHERE ...) restricts the rows an aggregate sees. It also assumes you know how count and sum treat NULL. It uses the orders table from earlier chapters. Here you combine FILTER with the options that live inside an aggregate call: DISTINCT, ORDER BY, and the list-building aggregates string_agg and array_agg.
Where each piece goes
An aggregate call in PostgreSQL has this shape:
aggregate_name ( [ DISTINCT ] expression [, ...] [ ORDER BY ... ] ) [ FILTER ( WHERE condition ) ]DISTINCT and ORDER BY go inside the parentheses. FILTER goes after the closing parenthesis. This is the most common source of syntax errors, because it is tempting to write the condition next to the other options.
Conceptually, the aggregate processes its input in this order:
Each aggregate call in a query does this separately. The filter on one column does not affect any other column in the same SELECT.
Sample data
The examples below use these rows. Run them against the orders table to reproduce the shown results.
INSERT INTO orders (id, customer_id, status, amount, created_at) VALUES
(1, 10, 'paid', 20.00, '2026-01-05 10:00+00'),
(2, 10, 'refunded', 15.00, '2026-01-06 10:00+00'),
(3, 10, 'paid', 30.00, '2026-01-07 10:00+00'),
(4, 20, 'pending', 12.50, '2026-01-08 10:00+00'),
(5, 20, 'paid', 40.00, '2026-01-09 10:00+00'),
(6, 30, 'refunded', 8.00, '2026-01-10 10:00+00'),
(7, 30, 'refunded', 9.00, '2026-01-04 10:00+00');FILTER with count(DISTINCT ...)
count(*) counts rows, but often you want to count distinct entities, such as customers rather than orders. Adding DISTINCT inside the call and FILTER after it gives you a conditional distinct count:
SELECT
count(DISTINCT customer_id) AS total_customers,
count(DISTINCT customer_id) FILTER (WHERE status = 'refunded') AS customers_with_refunds
FROM orders;With the sample data this returns 3 and 2. Customers 10 and 30 have refunded orders. Customer 20 does not.
The filter runs first. Only refunded rows reach the DISTINCT step, so customer 30, who has two refunded orders, is counted once.
Without FILTER, the equivalent CASE form is count(DISTINCT CASE WHEN status = 'refunded' THEN customer_id END). It works because count(expr) skips NULLs. The FILTER version keeps the condition out of the counted expression, which is easier to read when the expression is itself complicated.
FILTER with ORDER BY inside array_agg
array_agg collects values into an array. The order of elements is otherwise unspecified, so add ORDER BY inside the call whenever the order matters:
SELECT
customer_id,
array_agg(id ORDER BY created_at DESC) FILTER (WHERE status = 'refunded') AS refunded_ids
FROM orders
GROUP BY customer_id
ORDER BY customer_id;| customer_id | refunded_ids |
|---|---|
| 10 | {2} |
| 20 | NULL |
| 30 | {6,7} |
Customer 30's order 6 is newer than order 7, so the descending sort puts 6 first. Customer 20 has no refunded orders, so the filter leaves the aggregate with no input rows.
The ORDER BY inside the call only orders the elements of that aggregate. It has no effect on the order of the output rows. The final ORDER BY customer_id at the end of the query controls that.
FILTER with string_agg
string_agg(value, delimiter) joins text values into one string. It combines with FILTER and ORDER BY in the same way:
SELECT
customer_id,
string_agg(id::text, ', ' ORDER BY id) FILTER (WHERE status = 'paid') AS paid_order_ids
FROM orders
GROUP BY customer_id
ORDER BY customer_id;Customer 10 gets 1, 3, customer 20 gets 5, and customer 30 gets NULL. string_agg needs text input, so the integer id is cast with ::text.
DISTINCT together with ORDER BY
You can use both DISTINCT and ORDER BY in one aggregate call, with one restriction. PostgreSQL requires every ORDER BY expression to appear in the argument list. Deduplication is done on the argument values, so sorting by something else would be ambiguous. Suppose a customer has two refunded orders with different dates. Which date would decide the position of a duplicate value?
This works:
SELECT
customer_id,
string_agg(DISTINCT status, ', ' ORDER BY status) FILTER (WHERE amount >= 15) AS statuses_for_larger_orders
FROM orders
GROUP BY customer_id
ORDER BY customer_id;| customer_id | statuses_for_larger_orders |
|---|---|
| 10 | paid, refunded |
| 20 | paid |
| 30 | NULL |
Customer 10 has two paid orders of 15 or more, but paid appears once. Customer 30 has only small orders, so every row is filtered out.
This fails:
-- Do not run: raises an error
SELECT array_agg(DISTINCT status ORDER BY created_at) FROM orders;PostgreSQL reports in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list. Order by the same expression you deduplicate, as in array_agg(DISTINCT status ORDER BY status). If you need the order of a different column, deduplicate in a subquery first and aggregate the result.
NULLs: what arrays and strings do with them
The two list aggregates treat NULL input values differently. array_agg keeps NULLs as array elements. string_agg skips them:
SELECT
array_agg(x) AS as_array,
string_agg(x, ',') AS as_string
FROM (VALUES ('a'), (NULL), ('b')) AS t(x);The result is {a,NULL,b} for the array and a,b for the string. If you do not want NULL elements in an array, exclude them with the filter:
SELECT array_agg(x) FILTER (WHERE x IS NOT NULL) AS non_null_values
FROM (VALUES ('a'), (NULL), ('b')) AS t(x);This is a good use of FILTER even when you have no business condition, because the intent is explicit.
Empty results: NULL, not an empty array or string
You saw above that customer 20 got NULL for refunded_ids. When no rows pass the filter, array_agg and string_agg return NULL, the same as sum. Only count returns 0.
Decide what your consumer needs. A report that prints "none" and an application that iterates over an array need different defaults. Use coalesce to supply them:
SELECT
customer_id,
coalesce(array_agg(id ORDER BY id) FILTER (WHERE status = 'refunded'), '{}') AS refunded_ids,
coalesce(string_agg(id::text, ', ' ORDER BY id) FILTER (WHERE status = 'refunded'), '') AS refunded_text
FROM orders
GROUP BY customer_id
ORDER BY customer_id;The literal '{}' is read as an empty array of the right type because coalesce matches the type of its first argument. Customer 20 now gets {} and an empty string.
Keep NULL when "no matching rows" and "an empty list" should be distinguishable, or when a downstream tool treats NULL as missing. Replace it when you are feeding a client that cannot handle NULL.
FILTER with ordered-set aggregates
Some aggregates take their ordering as part of their definition, using WITHIN GROUP (ORDER BY ...). These are the ordered-set aggregates, such as percentile_cont and mode. FILTER goes after the WITHIN GROUP clause:
SELECT
customer_id,
percentile_cont(0.5) WITHIN GROUP (ORDER BY amount)
FILTER (WHERE status = 'paid') AS median_paid_amount
FROM orders
GROUP BY customer_id
ORDER BY customer_id;Customer 10 has paid amounts 20 and 30, so the median is 25. Customer 20 has one paid order, so the median is 40. Customer 30 has none, so the result is NULL.
A combined report
Here is a single query that uses all the pieces from this chapter. For each customer it reports the number of distinct statuses, the newest refunded order, and a readable list of paid order ids:
SELECT
customer_id,
count(DISTINCT status) AS distinct_statuses,
(array_agg(id ORDER BY created_at DESC) FILTER (WHERE status = 'refunded'))[1] AS latest_refunded_id,
coalesce(string_agg(id::text, ', ' ORDER BY created_at) FILTER (WHERE status = 'paid'), 'none') AS paid_ids
FROM orders
GROUP BY customer_id
ORDER BY customer_id;| customer_id | distinct_statuses | latest_refunded_id | paid_ids |
|---|---|---|---|
| 10 | 2 | 2 | 1, 3 |
| 20 | 2 | NULL | 5 |
| 30 | 1 | 6 | none |
Indexing the result with [1] takes the first element of the array. For an empty or NULL array it yields NULL. For this "newest matching row" case, a sorted array is a compact approach. On large groups it collects every matching id, so if you only need one value, max(created_at) FILTER (...) or DISTINCT ON may be cheaper.
Common mistakes
- Putting FILTER inside the parentheses. It must follow the closing parenthesis.
- Ordering by a different column under DISTINCT. The
ORDER BYexpressions must be in the argument list. - Expecting an empty array. The result is NULL when nothing matches, unless you wrap it in
coalesce. - Forgetting the order. An
array_aggorstring_aggwithoutORDER BYcan return different element orders from run to run. - Assuming string_agg keeps NULLs. It skips them, so the output may be shorter than the group.
Exercise
Using the sample data, write a query that returns one row per customer with (a) the number of distinct statuses among orders of at least 15.00, counted with count(DISTINCT ...) and FILTER, and (b) a comma-separated string of the paid order ids sorted from newest to oldest, or the text 'none' if the customer has no paid orders. What do customers 10, 20 and 30 get for each column?
Show answer
SELECT customerid, count(DISTINCT status) FILTER (WHERE amount >= 15) AS bigstatuses, coalesce(stringagg(id::text, ',' ORDER BY createdat DESC) FILTER (WHERE status = 'paid'), 'none') AS paidids FROM orders GROUP BY customerid ORDER BY customer_id; Customer 10 gets 2 (paid, refunded) and '3,1'. Customer 20 gets 1 (only the 40.00 paid order passes the amount test) and '5'. Customer 30 gets 0, because count returns 0 when every row is filtered out, and 'none'.
Exercise
The query SELECT arrayagg(DISTINCT customerid ORDER BY created_at) FROM orders fails. Why, and how do you change it so that it returns the distinct customer ids in ascending order, only for refunded orders?
Show answer
With DISTINCT, every ORDER BY expression must appear in the argument list, and createdat does not. Order by the deduplicated expression and add the filter after the parenthesis: SELECT arrayagg(DISTINCT customerid ORDER BY customerid) FILTER (WHERE status = 'refunded') FROM orders; With the sample data this returns {10,30}.