Import CSV File Into PostgreSQL Table
Summary: in this tutorial, we will show you various ways to import a CSV file into a PostgreSQL table.
First, create a new table named persons
with the following columns:
id
: the person idfirst_name
: first namelast_name:
last namedob
date of birthemail
: the email address
Second, prepare a CSV data file with the following format:
The path of the CSV file is as follows: C:\sampledb\persons.csv
Import a CSV file into a table using COPY statement
To import this CSV file into the persons
table, you use COPY
statement as follows:
PostgreSQL gives back the following message:
It means that two rows have been copied. Let’s check the persons
table.
It works as expected.
Let’s dive into the COPY statement in more detail.
First, you specify the table with column names after the COPY
keyword. The order of the columns must be the same as the ones in the CSV file. In case the CSV file contains all columns of the table, you don’t need to specify them explicitly, for example:
Second, you put the CSV file path after the FROM
keyword. Because CSV file format is used, you need to specify DELIMITER
as well as CSV
clauses.
Third, specify the HEADER
keyword to indicate that the CSV file contains a header. When the COPY
command imports data, it ignores the header of the file.
Notice that the file must be read directly by the PostgreSQL server, not by the client application. Therefore, it must be accessible by the PostgreSQL server machine. Also, you need to have superuser access to execute the COPY
statement successfully.
Import CSV file into a table using pgAdmin
In case you need to import a CSV file from your computer into a table on the PostgreSQL database server, you can use the pgAdmin.
The following statement truncates the persons
table so that you can re-import the data.
First, right-click the persons
table and select the Import/Export… menu item:
Second, (1) switch to import, (2) browse to the import file, (3) select the format as CSV, (4) select the delimiter as comma (,
):
Third, click the columns tab, uncheck the id column, and click the OK button:
Finally, wait for the import process to complete. The following shows the dialog that informs you of the progress of the import:
In this tutorial, you have learned how to import data from a CSV file into a table on the PostgreSQL database server using the COPY
statement and pgAdmin tool.