0

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.

example:

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,"horse"
  • 2
    Use copy, see e.g. here: stackoverflow.com/a/61636282/330315 – a_horse_with_no_name May 12 at 18:01
  • Wow, it's hard to believe they left that out of the command line version. Thank you! – raphael75 May 12 at 19:14
  • No idea what you mean with "left that out", the solution using copy will work "with the command line" – a_horse_with_no_name May 12 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 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. – a_horse_with_no_name May 12 at 19:59
1

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)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.