How to import CSV file to the Database

herminiotorres

Herminio Torres

Posted on December 19, 2023

How to import CSV file to the Database

How to import CSV data file to the database and populate the table.

Imagine you have this migration in your application with the following columns:

create table(:users) do
  add :first_name, :string, null: false
  add :last_name, :string, null: false
  add :username, :string, null: false
  add :email, :string, null: false
end
Enter fullscreen mode Exit fullscreen mode

And this would be the CSV file:

First Name,Last Name,Username,Email
John,Doe,john_doe,john@doe.com
Jane,Doe,jane_doe,jane@doe.com
...
Enter fullscreen mode Exit fullscreen mode

And how can I import my CSV file to the users' table on the database?

~$ psql -U user -d database <<USERS
COPY users(first_name, last_name, username, email) FROM '/path/to/users.csv' DELIMITER ',' CSV HEADER;
USERS
Enter fullscreen mode Exit fullscreen mode

After finishing, you will receive an output with COPY 2 the number of copies in your table.

💖 💪 🙅 🚩
herminiotorres
Herminio Torres

Posted on December 19, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to import CSV file to the Database