Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL row to string

I have a result from a query like the below, which does not have a fixed number of columns

ID  COL1    COL2    COL3    COL4
-------------------------------------
1   VAL11   VAL12   VAL13   VAL14
2   VAL21   VAL22   VAL23   VAL24

Now I want the result to be something like this.

RESULT
-----------------------------------------------------
ID:1, COL1:VAL11, COL2:VAL12, COL3:VAL13, COL4:VAL14
ID:2, COL1:VAL21, COL2:VAL22, COL3:VAL23, COL4:VAL24

Please help.

like image 398
Nancy Avatar asked Mar 25 '26 18:03

Nancy


2 Answers

The quick and dirty way, but without the column names and including NULL values:

SELECT tbl::text
FROM   tbl;

The slow & sure way:

SELECT array_to_string(ARRAY[
          'ID:'   || id
         ,'COL1:' || col1
         ,'COL2:' || col2
        ], ', ')  AS result
FROM    tbl;

If a column holds a NULL value, it will be missing in the result. I do not just concatenate, because NULL values would nullify the whole row.
array_to_string() makes sure that commas are only inserted where needed.


PostgreSQL 9.1 introduced the new function concat_ws() (much like the one in MySQL) with which we can further simplify:

SELECT concat_ws(', '
          'ID:'   || id
         ,'COL1:' || col1
         ,'COL2:' || col2
        ) AS result
FROM    tbl;
like image 152
Erwin Brandstetter Avatar answered Mar 27 '26 12:03

Erwin Brandstetter


SELECT
            'ID:'  ||coalesce(id::text,   '<null>')
    ||', '||'COL1:'||coalesce(col1::text, '<null>')
    ||', '||'COL2:'||coalesce(col2::text, '<null>')
FROM tbl;

You can use this SQL to generate the first one for you (in case there're lot's of columns):

SELECT E'SELECT \n'||string_agg(trim(stmt), E' \n')||E'\n  FROM tbl;'
  FROM (SELECT
    CASE WHEN a.attnum > 1 THEN $$||', '||$$ ELSE '' END ||
    $$'$$||upper(a.attname)||$$:'||coalesce($$||quote_ident(a.attname)||
    $$::text, '<null>')$$ AS stmt
  FROM pg_attribute a, pg_class t
 WHERE t.relkind='r' AND t.relname = 'tbl' AND a.attrelid = t.oid
   AND NOT a.attisdropped AND a.attnum > 0) AS s;
like image 23
vyegorov Avatar answered Mar 27 '26 13:03

vyegorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!