Export a table to a CSV file
Low risk
What do risk levels mean?
- Read-only
- Inspects state without changing anything.
- Low risk
- Reversible with a routine follow-up command.
- Medium risk
- Changes state; undo path documented.
- Destructive
- Deletes or overwrites; confirmation required.
Writes the contents of a table to a CSV file on the server so you can share data with other tools or archive a snapshot.
postgresqlexportcsvdata
Parameters
Name of the table to export.
Path for the output CSV file.
Commands
Inspect how many rows will be exported
psql -c "SELECT count(*) AS row_count FROM <table_name>;"Export all rows to a CSV file with a header row
psql -c "\copy <table_name> TO 'export.csv' CSV HEADER"Verification
wc -l export.csvLine count is row count plus one (for the header); the file is not empty.
Undo
Not undoable
The exported file itself consumes disk space; delete it manually when it is no longer needed.
Pitfalls
- \copy writes to the client machine, not the server; the file path is local.
- Large tables may produce multi-gigabyte files; ensure enough disk space.
- CSV escaping follows PostgreSQL rules; some spreadsheet tools may interpret quotes differently.
- Sensitive data in the export is not encrypted; handle the file accordingly.