PostgreSQL 17.9
ARRAY_AGG([DISTINCT] expression [ORDER BY sort_expression [ASC | DESC] [NULLS FIRST | NULLS LAST]])- [ ]optional part
- a | bone of the options
- DISTINCT
- Collect only unique valuesKeywordOptional
- expression
- Expression whose values are collected into the array
- ORDER BY sort_expression [ASC | DESC] [NULLS FIRST | NULLS LAST]
- Order of elements, arbitrary without itOptional
- sort_expression
- Column or expression to sort by
- ASC | DESC
- Direction, ASC by defaultKeywordOptionalASCDESC
- NULLS FIRST | NULLS LAST
- Where NULLs go, by default last with ASC and first with DESCKeywordOptionalNULLS FIRSTNULLS LAST
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.9
SELECT ARRAY_AGG(
n
ORDER BY n DESC
)
FROM GENERATE_SERIES(1, 5) AS n;Names by status with GROUP BY
PostgreSQL 17.9
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.
Array elements are numbered from 1: the expression (ARRAY_AGG(member_name ORDER BY birthday))[1] returns the name of the oldest family member.