How to export postgresql query to CSV

Today I’ve had a task to export couple of PostgreSQL (v10) to a CSV for some data analytics. Here’s how I did this:

\copy (select * from supersecrettable;) To '/home/nedko/supersecrettable.csv' With CSV DELIMITER ',' HEADER

It’s super easy, but, BUT how do you do the same exercise but with multi-line query? I hit the дърво before I find the way. Because if I paste the query with the \copy parameter and everything else I violate some parameter requirements and I got

\copy: parse error at end of line

I’ve found a workaround (not the cleanest way to do this, but it works at least). Just paste the query without the \copy and then navigate back to the beginning to add it manually.

Leave a Comment

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