0

I tried to export a select query result to a csv file. I used Postgres \copy metacommand and command line (psql) to do it. But I got a Syntax error and can't understand why. The Query looks fine to me. Maybe the reason for using metacommand instead of COPY? The query

\copy
  (
    SELECT geo_name, state_us_abbreviation, housing_unit_count_100_percent
    FROM us_counties_2010
    ORDER BY housing_unit_count_100_percent DESC
    LIMIT 20
  )
TO '/username/Desktop/us_counties_2010_export.csv' 
WITH(FORMAT CSV, HEADER, DELIMITER '|');

Error message

ERROR:  syntax error at or near "TO"
LINE 7: TO '/username/Desktop/us_counties_2010_export.csv'
5
  • 2
    To rule out the obvious: you are using psql to run this? Commented May 10, 2021 at 11:25
  • using psql run psql -d yourdb -c "COPY .... TO STDOUT " > /username/Desktop/us_counties_2010_export.csv Commented May 10, 2021 at 11:52
  • Please show the error message. Commented May 10, 2021 at 14:52
  • @a_horse_with_no_name yes psql Commented May 10, 2021 at 16:14
  • Laurenz Albe - Error message added Commented May 10, 2021 at 16:16

1 Answer 1

2

\copy is a metacommand given to psql, not a regular command sent to the server. So like other metacommands, the entire \copy command must all be given on one line and doesn't end in a ; but rather a newline.

If you look closely, you will see the first error you got was \copy: arguments required

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

1 Comment

worked in one line and without ; Thanks a lot!

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.