STRING_AGG
MySQL equivalent:
Joins values from a group of rows into one string with a delimiter.
PostgreSQL 17.9
STRING_AGG([DISTINCT] expression, delimiter [ORDER BY sort_expression [ASC | DESC] [NULLS FIRST | NULLS LAST]])- [ ]optional part
- a | bone of the options
- DISTINCT
- Join only unique valuesKeywordOptional
- expression
- Text expression whose values are joined; a number must be cast to texttext
- delimiter
- Delimiter between valuestext
- ORDER BY sort_expression [ASC | DESC] [NULLS FIRST | NULLS LAST]
- Order of values, 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
A string (text); NULLs are skipped, NULL if all values are NULL
Examples
All names separated by commas
PostgreSQL 17.9
SELECT STRING_AGG(member_name, ', ')
FROM FamilyMembers;Names by status in alphabetical order
PostgreSQL 17.9
SELECT status,
STRING_AGG(
member_name,
', '
ORDER BY member_name
) AS members
FROM FamilyMembers
GROUP BY status
ORDER BY status;Numbers via ::text and unique statuses
PostgreSQL 17.9
SELECT STRING_AGG(
member_id::text,
','
ORDER BY member_id
) AS ids,
STRING_AGG(DISTINCT status, ', ') AS statuses
FROM FamilyMembers;Details
The values must be text: STRING_AGG(member_id, ',') causes an error, while STRING_AGG(member_id::text, ',') works.
Together with DISTINCT, sort_expression must match expression.