Sub topic 8
FILTER with DISTINCT, ORDER BY, string_agg and array_agg
This chapter assumes you know basic SELECT, WHERE, ORDER BY, and aggregate functions such as count and sum. It also assumes you understand that NULL represents a missing or unknown value in SQL.
The FILTER clause does not apply only to numeric totals. PostgreSQL also supports it with aggregates that build lists or strings. The filter is written after the aggregate call:
aggregate_expression(...) FILTER (WHERE condition)This position matters. Options such as DISTINCT and ORDER BY belong inside the parentheses. FILTER comes after the closing parenthesis.
Filtering a list aggregate
array_agg collects values into a PostgreSQL array. The following query returns the refunded order IDs for each customer:
SELECT
customer_id,
array_agg(id) FILTER (WHERE status = 'refunded') AS refunded_order_ids
FROM orders
GROUP BY customer_id;Each customer receives an array containing only IDs from refunded orders. A customer with no refunded orders receives NULL, because no input row passed the filter.
You can control the order of values inside the array by placing ORDER BY inside array_agg:
SELECT
customer_id,
array_agg(id ORDER BY created_at)
FILTER (WHERE status = 'refunded') AS refunded_order_ids
FROM orders
GROUP BY customer_id;The rows are still grouped by customer, but the IDs inside each array follow creation time.
A common mistake is to put ORDER BY after FILTER. That orders the result rows rather than the values inside each array:
SELECT
customer_id,
array_agg(id) FILTER (WHERE status = 'refunded') AS refunded_order_ids
FROM orders
GROUP BY customer_id
ORDER BY customer_id;Here, ORDER BY customer_id sorts customers. It does not sort the IDs in each array.
Combining FILTER with DISTINCT
DISTINCT removes duplicate input values before the aggregate produces its result. For example, this query lists the different statuses observed for each customer:
SELECT
customer_id,
array_agg(DISTINCT status ORDER BY status) AS statuses_seen
FROM orders
GROUP BY customer_id;The result has no repeated status values, and the values are sorted alphabetically.
You can combine DISTINCT, ORDER BY, and FILTER in one aggregate:
SELECT
customer_id,
array_agg(
DISTINCT status
ORDER BY status
) FILTER (WHERE status <> 'pending') AS completed_statuses
FROM orders
GROUP BY customer_id;The filter removes pending rows. DISTINCT removes repeated statuses from the remaining rows. ORDER BY sorts the final array.
PostgreSQL requires expressions used in an aggregate's ORDER BY to be compatible with DISTINCT. Ordering by the same expression, as in this example, avoids that error.
Building readable strings with string_agg
string_agg joins text values with a separator. This query creates a comma-separated list of refunded order IDs:
SELECT
customer_id,
string_agg(
id::text,
', ' ORDER BY created_at
) FILTER (WHERE status = 'refunded') AS refunded_order_ids
FROM orders
GROUP BY customer_id;The id::text expression converts the numeric ID to text. The separator is ', '. The order expression is inside the aggregate call, before the closing parenthesis.
You can also create a distinct, sorted list of statuses:
SELECT
customer_id,
string_agg(DISTINCT status, ', ' ORDER BY status) AS statuses_seen
FROM orders
GROUP BY customer_id;If no row passes the filter, string_agg returns NULL, just like array_agg. Use coalesce when a report should show an empty string or array instead:
SELECT
customer_id,
coalesce(
string_agg(DISTINCT status, ', ' ORDER BY status)
FILTER (WHERE status <> 'pending'),
''
) AS non_pending_statuses
FROM orders
GROUP BY customer_id;How the clauses work together
The filter is local to its aggregate. Two aggregates in the same SELECT statement can receive different subsets of the same group:
SELECT
customer_id,
array_agg(id ORDER BY created_at)
FILTER (WHERE status = 'paid') AS paid_order_ids,
string_agg(DISTINCT status, ', ' ORDER BY status)
FILTER (WHERE status <> 'pending') AS active_statuses
FROM orders
GROUP BY customer_id;FILTER applies only to aggregate functions. It cannot be attached directly to an ordinary scalar expression such as lower(status). For ordinary row filtering, use WHERE.
Exercise
Write a query that returns each customer and a comma-separated, alphabetically sorted list of distinct refunded status values. Customers with no refunded rows should display an empty string.
Show answer
SELECT customerid, coalesce(stringagg(DISTINCT status, ', ' ORDER BY status) FILTER (WHERE status = 'refunded'), '') AS refundedstatuses FROM orders GROUP BY customerid;