Import/Export CSV files in PostgreSQL

The PostgreSQL COPY command can be used to both import from and export to a CSV file.

IMPORT:

Import CSV into table table_name:

COPY table_name FROM '/directory/path/filename.csv' DELIMITER ',' CSV;

Obviously you can change delimiter character with DELIMITER.

Import CSV into table table_name specifying the columns to use:

COPY table_name("name", “value”, “count”) FROM 'filename.csv' DELIMITER ',' CSV; 

EXPORT:

Export table to a CSV file:

COPY table_name TO 'filename.csv' DELIMITER ',' CSV HEADER; 

Export specific columns from a table to a CSV file:

COPY (SELECT name, value FROM table_name) TO 'filename.csv' CSV;

Leave a Reply

Your email address will not be published. Required fields are marked *