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.

Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

If you like this post, then please share it with others.
Please follow, I will share my experience towards the success of Database Research and Development Activity.

I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.

More from

Leave a Reply

Be the First to Comment!

Notify of