How to concatenate all results from a table row?

It is impossible to find a solution to do something like:

SELECT CONCAT_WS(',', ( SELECT * FROM table WHERE id = 1 )) 

How to do it in PostgreSQL?

+3
source share
1 answer

Quick and dirty:

 SELECT t::text FROM tbl t WHERE id = 1; 
  • t is an alias for the table and is not strictly necessary. You can also use the name of the source table. But if you have a column of the same name, it takes precedence.

  • So, t represents the table row type, which is automatically forcibly converted to a text representation on the output.
    I added an explicit cast to make it text internally as well - in case you want to do something with it ...
    t::text is a short Postgres notation for cast (t AS text) SQL standard, which you can also use. Details in the manual.

  • You can trim (single!) Leading and trailing parentheses that indicate the type of string:

     SELECT right(left(t::text, -1), -1)) FROM tbl AS t WHERE id = 1; 
  • "dirty" because you get Postgres string notation, the separator turns out to be only the comma you requested, but some values ​​are also escaped and / or duplicated if necessary.

+2
source

Source: https://habr.com/ru/post/1271514/


All Articles