The default output format for a query is something like this:
ID | field1
-----------
1 | val1
2 | val2
Is it possible in SQL to change it to a CSV format like this?
ID , field1
1 , val1
2 , val2
Currently, I am converting fields to string values and then concatenating them using the ||
operator, e.g.
SELECT ID::text || ', ' || field1 ...
FROM ...
But this is really cumbersome to write, and not very readable either.
Is there a more succinct way of doing this without converting to strings?
This isn't a duplicate of Export remote Postgres table to CSV file on local machine because as shown in my example, I am looking to output in CSV, not store the output as a CSV file.
Best Answer
You can copy a query results directly into a CSV file, e.g.
The file
/data/test.csv:
Use the function
concat_ws()
to get an output in expected format. Base types will be automatically converted to texts: