0

On PostgreSQL 11, I’d like to output the rows of a table as a comma-separated list of strings:

id,info,name,message

I tried the following query:

SELECT array_to_string(array_agg(t), ',', '')                                                                                                                          
FROM (                                                                      
    SELECT id, info, name, message
    FROM myschema.mytable
) t;

But this outputs:

(1,foo,bar,baz),(2,qux,zap,xen)

In constrast, the desired result should look like:

1,foo,bar,baz
2,qux,zap,xen

What would be the correct query?

2 Answers 2

1

You seem to want:

SELECT id, CONCAT_WS(',', info, name, message)
FROM myschema.mytable;

No aggregation is necessary. The values you want are all in one row.

You can, of course, include id in the string instead of as a separate column:

SELECT CONCAT_WS(',', id, info, name, message)
FROM myschema.mytable;
Sign up to request clarification or add additional context in comments.

Comments

0

I could solve it with the following function:

CREATE OR REPLACE FUNCTION myschema.get_foo()
RETURNS SETOF text AS $$
BEGIN
    RETURN QUERY
        SELECT COALESCE(array_to_string(array[id::text, info::text, name::text, message::text], ','), ''::text)
        FROM myschema.mytable;
END;
$$ LANGUAGE plpgsql;

And then run:

SELECT * FROM myschema.get_foo();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.