Crampus
Crampus

Reputation: 491

Problem with postgres \copy command for export query resullt to file

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'

Upvotes: 0

Views: 1746

Answers (1)

jjanes
jjanes

Reputation: 44323

\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

Upvotes: 2

Related Questions