Herminio Torres
Posted on December 19, 2023
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
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
...
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
After finishing, you will receive an output with COPY 2
the number of copies in your table.
💖 💪 🙅 🚩
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.