\copy (SELECT id, email FROM users WHERE active) TO 'active_users.csv' CSV HEADER

Category: Databases & SQL

\copy (SELECT id, email FROM users WHERE active) TO 'active_users.csv' CSV HEADER

Export a query result to a CSV file

Unlike \copy with a table name, this accepts a parenthesized SELECT so you export only the rows you want. The file lands on the client machine. Related: \copy users TO 'users.csv' CSV HEADER.
Looking for more? Search all 7,657 commands — works offline, in English or Spanish, and fixes typos.