0

I need to execute a query from a file and write the output of it to a CSV file. I want to keep the delimiter as ;. I have tried below queries.

psql -h localhost -p 5432 -U postgres -d postgres -f \path\to\sqlQuery.sql -o \path\to\result\result.csv  

This query puts the result into a file but it is in a postgres result tabular format.

psql -h localhost -p 5432 -U postgres -d postgres -f copy(\path\to\sqlQuery.sql) to \path\to\result.csv csv header;  

Above query is giving me a syntax error.

I'm looking for a way to use COPY command and \f or -f together so I'll be able to exceute the query from a file and also write the output to another CSV file with specified delimiter.

1
  • You might try psql -t -A -F"," -f in_file.sql -o out_file.csv. This doesn't give you value quoting though. Commented Aug 13, 2019 at 12:50

1 Answer 1

1

Change your SQL script to use COPY:

COPY (/* your query */) TO STDOUT
   (FORMAT 'csv', DELIMITER ';');
Sign up to request clarification or add additional context in comments.

Comments

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.