PostgreSQL – Specify Field Enclosure in PSQL Command Line

postgresqlpsql

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"

Best Answer

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)