Exporting results of a query from Postgres as a CSV

Through the psql client, you can use the following syntax to export to a CSV formatted file on the local filesystem:

\copy (SELECT * FROM table WHERE 1) TO '/tmp/foo.csv' With CSV HEADER

This results in a CSV being written to /tmp/foo.csv and uses the table field names as headers. If you don’t want headers, omit the HEADER part of the above query.

Documentation on Postgres COPY command:

https://www.postgresql.org/docs/9.2/sql-copy.html

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.