How to import CSV File Data into PostgreSQL table?
In PostgreSQL, importing data from a CSV file into a table is straightforward using the COPY command or the \COPY meta-command in psql. These methods efficiently load large datasets into PostgreSQL tables with minimal configuration.
Method 1: Using the COPY Command from a File Path
The COPY command is executed within SQL and requires that PostgreSQL has direct access to the file path. This method works well if you are loading the CSV file from the server where PostgreSQL is hosted.
Syntax:
COPY table_name (column1, column2, ...) FROM '/path/to/your/file.csv' WITH (FORMAT CSV, HEADER);
Explanation:
Example Code:
-- Import data from a CSV file into a PostgreSQL table
COPY employees (id, name, department, salary) -- Target table and columns
FROM '/tmp/employees.csv' -- File path to CSV file
WITH (FORMAT CSV, HEADER); -- CSV format and includes header row
Explanation:
Note: This approach requires read access to the file on the server’s filesystem.
Method 2: Using \COPY in psql for Local File Imports
The \COPY meta-command in psql allows you to load a CSV file from your local machine. It reads the file on the client side and then sends the data to the PostgreSQL server, which is helpful when running imports from a remote database.
Syntax:
\COPY table_name (column1, column2, ...) FROM '/local/path/to/your/file.csv' WITH (FORMAT CSV, HEADER);
Example Code:
# Connect to the database with psql and run \COPY
psql -U postgres -d my_database -c "\COPY employees (id, name, department, salary) FROM '/local/path/employees.csv' WITH (FORMAT CSV, HEADER);"
Explanation:
Additional Options for COPY and \COPY
Important Notes:
All PostgreSQL Questions, Answers, and Code Snippets Collection.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4