Importing Data into PostgreSQL from a CSV File

03-18-2020

If you’re using Postgres as a database and need to import data from a .csv file, it’s really easy to do using psql.

Before you start, you’l need:
1) psql running in an interactive terminal
2) A Postgres database with a table you want to import data, we’ll call it _user_data_
3) Data in a .csv file

Your .csv file should have matching headers to the column names in your Postgres table

Example file:
users.csv

1
2
3
4
user_id,location,is_active,created_at
10,USA,true,2020-03-08
11,UK,true,5678,2020-03-09
...

To import use the COPY command:

1
COPY user_data from 'users.csv' WITH DELIMITER ',' CSV HEADER;

Result:
| user_id | location | is_active | created_at |
| :—— | :——- | :——– | :——— |
| 10 | USA | true | 2020-03-08 |
| 11 | UK | true | 2020-03-09 |