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

1 Answer 1

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)

answered May 12, 2020 at 18:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.