Discover how one simple function can turn many scattered rows into clear, grouped lists instantly!
Why Array aggregation with ARRAY_AGG in PostgreSQL? - Purpose & Use Cases
Imagine you have a list of students and their favorite subjects scattered across many rows in a table. You want to see all subjects each student likes grouped together in one place.
Manually collecting all subjects for each student means scanning the entire list repeatedly, writing complex code, or copying and pasting data by hand. This is slow, tiring, and easy to mess up.
Using ARRAY_AGG, you can quickly gather all subjects for each student into a neat list with a simple query. It groups data automatically, saving time and avoiding mistakes.
SELECT student, subject FROM favorites WHERE student = 'Alice'; -- then manually combine subjectsSELECT student, ARRAY_AGG(subject) FROM favorites GROUP BY student;
You can instantly see all related items for each group in one row, making data clearer and easier to use.
A teacher wants to see all books each student borrowed from the library in one list instead of checking many records separately.
Manually grouping data is slow and error-prone.
ARRAY_AGG collects related items into arrays automatically.
This makes data easier to read and work with.