string_agg, FILTER & friends
◈ 2 cardsCollapse groups into lists, and aggregate a subset inline.
Beyond count and sum
Postgres adds powerful aggregates:
string_agg(expr, sep ORDER BY ...)— concatenate group values into one stringarray_agg(expr)— collect them into an arraycount(*) FILTER (WHERE cond)— aggregate only the rows matching a condition, without a separate querycount(DISTINCT col)— count unique values
SELECT count(*) AS total,
count(*) FILTER (WHERE stock = 0) AS sold_out
FROM books;
FILTER is the clean way to get several differently-filtered counts in one pass.