2

I am wondering how to create or export a CSV file from SQL? Is there any function for that similar to pgsql2shp? I would appreciate your ideas, tip or solutions.

3 Answers 3

6

You can save a complete table as a file using this command:

COPY tablename TO STDOUT CSV

Ref: https://www.postgresql.org/docs/current/static/sql-copy.html

4

You can give this a try. But i believe there may be some syntax changes depending on the version.

COPY (SELECT foo,bar FROM whatever) TO ‘/tmp/dump.csv’ WITH CSV HEADER
2
  • I got this message: ERROR: could not open file "/dump.csv" for writing: Permission denied What should i do now? Btw, instead of the query above i wrote: COPY (SELECT * FROM table1) TO '/dump.csv' WITH CSV HEADER because proposed path does not exist.
    – Z77
    Commented Jun 14, 2010 at 8:17
  • Ok. I found out that problem was in path. So I changed path to: 'C:/Program Files/PostgreSQL/8.4/data/test.csv' and it works now. Obvoiusly some folders has restrictions.
    – Z77
    Commented Jun 14, 2010 at 11:03
1

If you use pgAdmin, you can export any query you run to a CSV file.

Not the answer you're looking for? Browse other questions tagged or ask your own question.