Import a CSV file into a table
Medium 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.
Loads data from a CSV file into an existing table so you can seed data, migrate from another system, or restore an archived snapshot.
postgresqlimportcsvdata
Parameters
Name of the target table.
Path to the CSV file to import.
Commands
Inspect the first two lines of the CSV to confirm columns and format
head -n 2 <csv_file>Load the CSV rows into the table
psql -c "\copy <table_name> FROM '<csv_file>' CSV HEADER"Verification
psql -c "SELECT count(*) AS row_count FROM <table_name>;"The row count reflects the number of data lines in the CSV file.
Undo
Remove all rows that were imported
psql -c "DELETE FROM <table_name>;"Pitfalls
- The target table must already exist with columns matching the CSV header.
- Duplicate rows or constraint violations will cause the entire import to fail; clean the CSV first or use ON CONFLICT handling.
- \copy reads from the client machine, not the server; the file path is local.
- Very large CSVs may exhaust memory or transaction logs; consider splitting them.