Import or Export a CSV File using PostgreSQL COPY Command

In this post, I demonstrate to export or import CSV data using the PostgreSQL COPY command.

The CSV files are most popular for the basic data migration activities. Database developer does not need to write or create any special database link between two servers.They can easily import data into CSV and export that CSV data into another server and also CSV file does not have any data length limitation like any other XLS file. User can store millions of records into CSV file.

Generally, this technique is preferred only for temporary purposes and if it is continued process, then user has to write some automated process like database server replication.

PostgreSQL provides the COPY command to import or export CSV data into PostgreSQL table.

Let me demonstrate this.

First, I create one table and import data from CSV file. I have already created one CSV file with sample data. Make sure that, your table column and CSV column would be same.

You can create this CSV file using comma delimited save as option of Microsoft excel.

Postgres CSV

Now COPY data from CSV file into this table.

After executing of COPY command, you can check the result.

Postgres CSV Tablel Data
Now I am going to add some more records into Table and then we export this data into CSV file.

Now export this data using the COPY command.

Now check your CSV file. You can find newly inserted data.

You can also define particular column or write full select statement in the COPY command.
Below is a sample script.

This is a full detailed example of postgres COPY command, please check this sample at your end and let me know for further assistance.

Anvesh Patel

Leave a Reply

Be the First to Comment!

Notify of