Search code examples
sqlpostgresqlstring-aggregation

How to concat strings in different row on Postgres


Let's say I have a table Foo and has a column name. I want to concatenate all names in Foo. For example

Table Foo

  Name
---------
  name1
  name2
  name3

I want to write a query that returns name1name2name3 or if possible name1,name2,name3.

I have done some googling and see concat function but it only concats columns of same row. I couldn't find a function or a way to accomplish this.


Solution

  • use string_agg

    SELECT string_agg(Foo, ', ') AS col
    FROM   tbl