PostgreSQL 18 reference · Aggregate Functions
PostgreSQL STRING_AGG() Function
Join a group's non-NULL values into one string with a separator, optionally in a given ORDER BY order.
PostgreSQL 18 Since 9.0
Syntax
string_agg(expression, delimiter ORDER BY ...)
Parameters
| Parameter | Description |
|---|---|
expression |
A column or expression. |
delimiter |
The separator. |
ORDER BY optional |
The order of values. |
Return value
Text, or NULL for no values.
Examples
SELECT department, string_agg(name, ', ' ORDER BY salary DESC) AS by_salary
FROM employees
GROUP BY department
ORDER BY department;
Output
department | by_salary -------------+------------------------------------------------------------- Engineering | Omar Haddad, Mei Chen, Jonas Berg, Priya Nair, Lucas Martin Management | Sofia Reyes Sales | Hannah Okafor, Diego Silva, Emma Novak Support | Ravi Kumar (4 rows)
Run this on your computer — see “Get Started” for setup.
SELECT string_agg(DISTINCT country, '/' ORDER BY country) AS countries FROM customers;
Output
countries -------------------------------------- Japan/Netherlands/Switzerland/UK/USA (1 row)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 9.0 | Added |
In other languages
STRING_AGG()· SQLiteGROUP_CONCAT()· SQLite
Related
ARRAY_AGG()· Collect a group's values, including NULLs, into an array, optionally in a given order.JSONB_AGG()· Aggregate a group's values or rows into a JSON array. json_agg() does the same but returns json.CONCAT_WS()· Join values with a separator between them, skipping NULLs. The first argument is the separator.- SQL Aggregate Functions · tutorial
- SQL GROUP BY · tutorial