Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

493
Views
Postgresql: run SQL query script and export to csv

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

SQL Interpolation in psql

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!