PostgreSQL 18 reference · Aggregate Functions

PostgreSQL ARRAY_AGG() Function

Collect a group's values, including NULLs, into an array, optionally in a given order.

PostgreSQL 18

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_agg(expression ORDER BY ...)

Parameters

ParameterDescription
expression A column or expression.
ORDER BY optional The order of the elements.

Return value

An array, or NULL for no rows.

Examples

An array per group
SELECT country, array_agg(split_part(name, ' ', 1) ORDER BY name) AS first_names
FROM customers
GROUP BY country
HAVING count(*) > 1
ORDER BY country;

Output

 country |               first_names
---------+------------------------------------------
 UK      | {Ada,Alan}
 USA     | {Barbara,Grace,Katherine,Linus,Margaret}
(2 rows)

Run this on your computer — see “Get Started” for setup.

Take the first element
SELECT (array_agg(name ORDER BY salary DESC))[1] AS top_earner FROM employees;

Output

 top_earner
-------------
 Sofia Reyes
(1 row)

Run this on your computer — see “Get Started” for setup.

In other languages

Was this page helpful?