string_agg(expression, delimiter)
suggest changeYou can concatenate strings, separated by a delimiter, with string_agg().
If your individuals table is:
| Name | Age | Country |
|---|---|---|
| Allie | 15 | USA |
| Amanda | 14 | USA |
| Alana | 20 | Russia |
You could write a SELECT ... GROUP BY statement to get names from each country:
SELECT string_agg(name, ', ' ORDER BY name) AS names, country
FROM individuals
GROUP BY country
ORDER BY country;
You need GROUP BY because string_agg() is an aggregate. Without ORDER BY inside string_agg, the order of names in each list is unspecified. The group order is also unspecified unless the query has ORDER BY.
Result:
| names | country |
|---|---|
| Alana | Russia |
| Allie, Amanda | USA |
More PostgreSQL aggregate functions are described here
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents