In psql if I have a field separator of ",", but there are commas in some fields, is it possible to specify a field enclosure character? I have looked through the documentation but I can't find it.


psql -h my_server -U my_user -d my_db -f sql_in/my_sql.sql -o sql_out/my_sql_out.csv -A -F','

-A will turn off the table formatting, -F specifies the field separator

If I have a row that looks like

id  types
1   zebra, lion, cat
2   horse

I want it to output to csv like:

1,"zebra, lion, cat"
  • 2
    Use copy, see e.g. here: stackoverflow.com/a/61636282/330315 May 12 '20 at 18:01
  • Wow, it's hard to believe they left that out of the command line version. Thank you!
    – raphael75
    May 12 '20 at 19:14
  • No idea what you mean with "left that out", the solution using copy will work "with the command line" May 12 '20 at 19:52
  • I meant command line in the sense of not using the psql shell. I meant straight from the bash command line like in my example in the original question.
    – raphael75
    May 12 '20 at 19:54
  • You just need to replace your query in my_sql.sql with copy (your query here...) to stdout and everything is fine. May 12 '20 at 19:59

In v12, psql introduced the --csv option. However, it still seems like the wrong tool for the job. You should use COPY or \copy instead (probably still invoked through psql)

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .