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.
The quick and dirty way, but without the column names and including NULL values:
The slow & sure way:
If a column holds a
NULLvalue, it will be missing in the result. I do not just concatenate, becauseNULLvalues 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: