2

I am running Postgresql version 9.3 on Ubuntu. I am wondering if there is a way to run a select statement stored in a script on a Postgres database and then send the results to csv. I know how to do either of the two by themselves; for example, exporting to csv (with the query explicitly written out):

COPY(select * from mytable) to 'path/to/file.csv' with csv header;

and running an sql script:

\i 'myscript.sql'

But after searching around I could not figure out how to do both in one action. That is, I could not figure out how to export to a csv when running a query script rather than typing out a select statement manually.

1
  • 1
    could you try explaining what you want a little better Commented Apr 19, 2017 at 20:04

1 Answer 1

3
\set query `cat /path/to/myscript.sql`
copy (:query) to '/path/to/file.csv' with csv header;

SQL Interpolation in psql

Sign up to request clarification or add additional context in comments.

1 Comment

make sure you do not have ; in myscript.sql and you have write permission to the folder where csv file will be exported.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.