2

Trying to make batch file that will get query from script file and put results into csv. Batch file code:

psql -h host -d test -U test -p 5432 -a -q -f C:\Users\test\Documents\my_query.sql TO STDOUT WITH CSV HEADER DELIMITER ';' > C:\Users\test\Documents\res.csv

In result file I'm getting result like this:

select *

from public.test

limit 3

    id    |    name     | count_01
----------+------------+---------------+
 11021555 | a       |             1 |
 39534568 | b       |             2 |
 11695210 | c       |             3 |

(3 rows)

How to get only script results without rows count and symbols like '|' or '+' and using ';' delimetres as in the usual csv file?

Working script:

psql -h host -d test -U test -p 5432 -q --quiet --no-align --field-separator=';' --file=C:\Users\test\Documents\my_query.sql --output=C:\Users\test\Documents\res.csv
4
  • 1
    Have you try "--no-align" and "--field-separator=" options? Commented Oct 5, 2021 at 15:15
  • Pretty sure you are getting the output of whatever is my_query.sql and never getting to the COPY. Add the contents of my_query.sql to your question. Commented Oct 5, 2021 at 15:34
  • Have you used the site search facility at the top of the page, when seeking examples of the use of the available options, you should have read? The first hit I found was this. Commented Oct 5, 2021 at 15:35
  • Using --field-separator=, will only work reliably if the data contain no commas... Commented Oct 6, 2021 at 7:18

2 Answers 2

2

From PostgreSQL v12 on, you can use the CSV output format of psql:

psql --quiet --csv --file=my_query.sql --output=res.csv

--quiet suppresses the psql welcome message.

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

2 Comments

When trying to add '--csv' getting an error 'psql: illegal option -- csv'
Then you are using a version older than v12 of psql.
0

Should work with

psql -h host -d dbname -U user -p port -a -q -f my_query.sql -o res.csv --record-separator=',' --csv

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.