Use COPY or \copy to write a PostgreSQL table (or query result) to a CSV file with optional header, delimiter, and encoding settings.
Run COPY table_name TO '/absolute/path/file.csv' WITH (FORMAT csv, HEADER true);
inside psql or any SQL client. PostgreSQL streams the table to the file on the server.
Use the psql meta-command \copy
. It sends the data through the client connection and writes to a file on your local machine, avoiding server-side file permissions.
FORMAT csv enables CSV output. HEADER true writes column names. DELIMITER ',', QUOTE '"', and ENCODING 'UTF8' let you match downstream requirements.
Instead of dumping the whole table, use COPY (SELECT col1, col2 FROM table_name WHERE ... ) TO ...
to apply filters or ordering.
Combine psql
and \copy
in an SSH session or direct the output to STDOUT
and pipe it: psql -c "COPY mytab TO STDOUT WITH (FORMAT csv, HEADER)" | gzip > mytab.csv.gz
.
Default CSV output writes nothing between delimiters for NULL. To change, CAST or COALESCE in a SELECT
inside COPY.
Run separate COPY/\copy commands or script them with psql. Each table needs its own target file.
Grant pg_read_server_files
(or superuser) for server-side COPY. Prefer \copy
for least-privilege workflows.
Yes. If the file already exists and the PostgreSQL server can write to it, COPY truncates and overwrites it. Use a new filename to avoid accidental loss.
Add DELIMITER '|'
(or any single character) in the WITH clause.
Target STDOUT and pipe to a compressor: psql -c "COPY mytab TO STDOUT WITH (FORMAT csv)" | gzip > mytab.csv.gz
.