How to Import data from a CSV file to PostgreSQL table

PostgreSQL is one of the most popular database which was used by millions of developers. PostgreSQL has more features and plugin supports when compared to other database which was available in the market.

In  my previous post I have showed you how to export PostgreSQL table to a CSV file, and in this post I am going to tell you how to import data from a csv file to PostgreSQL table.

Before stepping into it, you need to have a valid database first and then you need to have a csv file with data in it. This csv file was used to import into the PostgreSQL table. Make sure you have a valid data in this csv file.

As the first step create a database with the following query.

CREATE TABLE <table name>
  -- Your columns

After that make sure you have a valid csv file with data in it. Set the column type to String that will make you to easily import. Now execute the following command.

COPY <table name> FROM 'D:\data.csv' WITH DELIMITER ';' CSV HEADER;

Now all the rows must be copied in to your table <table name>.

Import data from a CSV file to table (with Foreign Keys):

Here you face some erros, if you try to import the data from a csv file to the table which you have foreign keys. SInce the columns are mapped with the other table data, you will face the errors.

To resolve this issue, you need to disable the Foreign Key first and then you need to import the data. Later you can enable the foreign keys in your table.

You can use the below code to enable and disable the foreign key constraint.

ALTER TABLE <table name> DISABLE CONSTRAINT <foreign key constraint name>;
ALTER TABLE <table name> ENABLE CONSTRAINT <foreign key constraint name>;

Please comment and write your views.

You may also like...

Leave a Reply

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