ARRAY_AGG helps you collect multiple values from rows into a single list. It makes it easy to see related data together.
Array aggregation with ARRAY_AGG in PostgreSQL
ARRAY_AGG(expression [ORDER BY expression])
The expression is the column or value you want to collect into an array.
You can use ORDER BY inside ARRAY_AGG to sort the values in the array.
SELECT department, ARRAY_AGG(employee_name) FROM employees GROUP BY department;
SELECT department, ARRAY_AGG(employee_name ORDER BY employee_name) FROM employees GROUP BY department;
SELECT ARRAY_AGG(product_name) FROM products WHERE category = 'Books';
This example creates an orders table, adds some orders, then groups products bought by each customer into arrays sorted alphabetically.
CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, customer_name TEXT, product_name TEXT ); INSERT INTO orders (customer_name, product_name) VALUES ('Alice', 'Book'), ('Alice', 'Pen'), ('Bob', 'Notebook'), ('Bob', 'Pen'), ('Bob', 'Eraser'); SELECT customer_name, ARRAY_AGG(product_name ORDER BY product_name) AS products_bought FROM orders GROUP BY customer_name ORDER BY customer_name;
ARRAY_AGG runs in O(n) time where n is the number of rows in the group.
It uses extra space to store the array for each group.
Common mistake: forgetting to use GROUP BY when aggregating, which causes errors or unexpected results.
Use ARRAY_AGG when you want to collect multiple values into one list. Use string_agg if you want a single string instead.
ARRAY_AGG collects multiple row values into a single array.
You can sort the array elements using ORDER BY inside ARRAY_AGG.
It is useful for grouping related data together in one row.