Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving psql output to csv file

I have a query written in a file located at /path/to/query. How can I save the output result to a csv file, without using COPY in the query? I tried the following command, but the output file's fields are separated by " | ".

psql -U username -d dbname -f /path/to/query -o /path/to/output/file -F ','
like image 451
Agrim Pathak Avatar asked May 26 '15 04:05

Agrim Pathak


People also ask

What is psql's \copy?

Using the \copy command to import data to a table on a PostgreSQL DB instance. The PostgreSQL \copy command is a meta-command available from the psql interactive client tool. You can use \copy to import data into a table on your RDS for PostgreSQL DB instance.


1 Answers

It is not explained in the documentation, but the -F option requires the -A option (unaligned table output) to work:

psql -U username -d dbname -f /path/to/query -o /path/to/output/file -F ',' -A

If you don't wish the headers in your csv, this means, without extra rows at the top and at the bottom, use the -t option too.

psql -U username -d dbname -f /path/to/query -o /path/to/output/file -F ',' -A -t

From the help:

-A, --no-align unaligned table output mode
-F, --field-separator=STRING set field separator (default: "|")
-t, --tuples-only print rows only

like image 173
Tom-db Avatar answered Nov 10 '22 09:11

Tom-db