11. Import & Export Data

Import CSV file into Table

(show you how to import CSV file into a table.)

  • You need to first create a table with all the columns

  • Second, prepare CSV data

Example 1

COPY persons(first_name, last_name, dob, email)
FROM 'C:\sampledb\persons.csv'
DELIMITER ','
CSV HEADER;

PostgreSQL gives back the following message:

COPY 2

It means that two rows have been copied.

Example 2

If CSV file contains all columns of the table, you don’t need to specify them explicitly

COPY sample_table_name
FROM 'C:\sampledb\sample_data.csv'
DELIMITER ','
CSV HEADER;

Export PostgreSQL Table to CSV file

(show you how to export tables to a CSV file.)

If you want to export all columns of a table

COPY persons TO 'C:\tmp\persons_db.csv' DELIMITER ',' CSV HEADER;

If you want to export specific columns of a table

COPY persons(first_name,last_name,email)
TO 'C:\tmp\persons_partial_db.csv' DELIMITER ',' CSV HEADER;

Last updated