Part 04 / Topic 6 of 6
string_agg and array_agg
Sometimes the summary you need is not a number but a list. string_agg collapses a group's values into one delimited string — with its own ORDER BY inside the brackets:
SELECT category_id,
string_agg(name, ', ' ORDER BY price DESC) AS products_priciest_first
FROM products
GROUP BY category_id
ORDER BY category_id;
category_id | products_priciest_first
-------------+---------------------------------------
1 | USB-C Cable
2 | Postgres Deep Dive, SQL for Beginners
3 | Desk Lamp
4 | Laptop Pro 14, Laptop Air 13
5 | Phone X, Phone Lite
6 | Coffee Maker, Chef Knife
(6 rows)
array_agg keeps them as a real Postgres array instead (arrays get their full lesson in Stage 3):
SELECT city, array_agg(first_name ORDER BY first_name) AS residents
FROM customers
WHERE city IS NOT NULL
GROUP BY city
ORDER BY city;
city | residents
---------+---------------
Chennai | {Meera}
Delhi | {Ravi}
London | {John}
Pune | {Asha,Vikram}
(4 rows)
These two turn "one row per thing" into "one row per group, things listed" — the shape emails, reports and APIs constantly want.
🧪 Quick quiz — answer from memory, then check.
- How do you control the order of names inside a
string_agglist? - What's the difference between
string_aggandarray_agg?
Show the answers
- An ORDER BY inside the call:
string_agg(name, ', ' ORDER BY name). - Same grouping behaviour; one returns a delimited text, the other a real array value.
Done here? The practice set for Part 4 — 7 exercises with solutions — is on the part page.