8

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 ','
Agrim Pathak
  • 3,047
  • 4
  • 27
  • 43

1 Answers1

11

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

Tom-db
  • 6,528
  • 3
  • 30
  • 44
  • It works. This is a little nit-picky, but how do I get rid of 2 extra lines: "SELECT " at the top and "(rows )" at the bottom? – Agrim Pathak May 26 '15 at 14:49
  • 1
    If you want only tuples, without other rows at bottom and at the top, use the option -t: `psql -U username -d dbname -f /path/to/query -o /path/to/output/file -F ',' -A -t`. – Tom-db May 26 '15 at 18:20
  • I tried that. I still saw "SELECT, though the row count at the bottom disappeared. – Agrim Pathak May 26 '15 at 18:39
  • This comes from the query. Post in your question the content of the file with the sql code. – Tom-db May 26 '15 at 18:56