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

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

Syntax

string_agg(expression, delimiter ORDER BY ...)

Parameters

ParameterDescription
expression A column or expression.
delimiter The separator.
ORDER BY optional The order of values.

Return value

Text, or NULL for no values.

Examples

Join per group
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.

Unique values in order
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

VersionChange
PostgreSQL 9.0Added

In other languages

Was this page helpful?