Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save definiteIymaybe/0abf96000f20addb8ba05531045df43a to your computer and use it in GitHub Desktop.
Save definiteIymaybe/0abf96000f20addb8ba05531045df43a to your computer and use it in GitHub Desktop.
Using PostgreSQL's COPY to import & export CSV files

Using PostgreSQL's COPY to import & export CSV files

COPY can read/write data not only from/to CSV, but also from/to binary files. For the import, the table must exist along with its columns matching CSV columns.

Export table to CSV

COPY <table> TO 'file.csv' DELIMITER ',' CSV HEADER; 

Export select results to CSV

COPY (SELECT <column1>,<column2> FROM <table>) TO '<file>.csv' CSV;

Export with explicit null character

COPY <table> TO 'file.csv' DELIMITER ',' CSV HEADER NULL as E''; 

Import CSV into table

COPY <table> FROM '<path>/<file>.csv' DELIMITER ',' CSV;

Import CSV into table with columns

COPY <table>("<column1>", "<column2>") FROM '<file>.csv' DELIMITER ',' CSV; 

Import CSV with explicit special character as delimiter

COPY <table> FROM '<file>.csv' DELIMITER E'\t' CSV; 

Import CSV by piping from STDIN

cat myfile | psql -c "COPY <table>  FROM STDIN"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment