How do you print the result of a PostgreSQL query in CSV or TSV format from the command line?

If you are using PostgreSQL 8.2 or newer, use this for CSV:

psql -c "COPY (<select query>) TO STDOUT WITH CSV"

and this of TSV, with proper NULLs:

psql -c "COPY (<select query>) TO STDOUT WITH NULL AS ''"

The CSV form will properly quote any fields that contain the double-quote character. See the PostgreSQL documentation of your specific version for more details and options for COPY.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)