PostgreSQL 17.5
ARRAY_AGG([DISTINCT] expression [ORDER BY ...])Parameters
- DISTINCTkeywordoptional
- Collect only unique values
- expression
- Expression whose values are collected into the array
- ORDER BYoptional
- Order of the elements in the array
Return value
An array of values of the same type, NULLs included; NULL for an empty set
Examples
Numbers into an array, descending
PostgreSQL 17.5
SELECT ARRAY_AGG(
n
ORDER BY n DESC
)
FROM GENERATE_SERIES(1, 5) AS n;Names by status with GROUP BY
PostgreSQL 17.5
SELECT status,
ARRAY_AGG(member_name) AS members
FROM FamilyMembers
GROUP BY status
ORDER BY status;Details
Unlike STRING_AGG, ARRAY_AGG does not skip NULL values. Without ORDER BY the order of the elements is not guaranteed.
Array elements are numbered from 1: the expression (ARRAY_AGG(member_name ORDER BY birthday))[1] returns the name of the oldest family member.