docs/docs/schema/postgres/postgres-guides/import-data-from-csv.mdx
import Thumbnail from '@site/src/components/Thumbnail';
You might have existing data stored in a CSV file that you need to import into your Postgres database. The following guide will show how to do so.
Let's assume we have the following CSV file, which is named profile.csv:
Let us create a table to match the data structure in your CSV file.
profile (
firstName TEXT,
lastName TEXT,
email VARCHAR
)
Connect to your Postgres database by using the psql command on the terminal:
psql postgres://<username>:<password>@<host>:<port>/<database>
# for example
psql postgres://postgres:postgres@localhost:5432/postgres
Once connected to the database, use the following command from inside psql to import the data:
\copy <table_name> from '</path/to/file/filename.csv>' delimiter ',' CSV HEADER;
# for example
\copy profile from '/Users/sarahlewis/documents/profile.csv' delimiter ',' CSV HEADER;
Your data would have been successfully copied into the Postgres database.
If a column's value is auto-generated, you can exclude it from the CSV file and allow the database to populate it automatically. However, you must make sure that the auto-generated column is defined as such in the table schema.
If a column is not present in the CSV file, you can call out the specific columns that you want to import from the CSV
into the database. Imagine our CSV from earlier doesn't contain the email column. We can import the data from the CSV
into the database by specifying only the columns we want to import:
# \copy <table_name> (<column1>, <column2>, ...) from '</path/to/file/filename.csv>' delimiter ',' CSV HEADER;
\copy profile (firstName, lastName) from '/Users/sarahlewis/documents/profile.csv' delimiter ',' CSV HEADER;
These columns' headers correspond to the appropriate column names in the table's schema.