0

Is there any alternative to the PostgreSQL array_agg() function so that it doesn't return values in the format: '{x,y,z,}'.
Can I have it return just: 'x,y,z' ?

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137

3 Answers3

9

In PostgreSQL 9.0 or later use string_agg(val, ',').
It returns a string with delimiters of your choosing.

array_agg(val) returns an array, no surprise there. The curly braces you see are integral part of array literals - the text representation of arrays.

In older versions (or any version really) you can substitute with array_to_string(array_agg(val), ',').

Or, quick'n'dirty: trim(array_agg(val)::text, '{}' - if values never start or end with curly braces.

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
4

If you are not on 9.0 yet (which has the already mentioned string_agg() function) you can use array_to_string() on the result of array_agg()

a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
2

Use the STRING_AGG function:

SELECT
  STRING_AGG(name, ',')
FROM
  person;
Dave Jarvis
  • 29,586
  • 38
  • 176
  • 304
Kouber Saparev
  • 6,817
  • 2
  • 25
  • 23