Importing data into a PostgreSQL database
The COPY and \COPY commands can not only be used to efficiently download data from tables to external files but can also be used to upload data from external files to tables. They are far more efficient at uploading data than an INSERT statement. There are a few reasons for this:
- When using
COPY, there is only one push of a data block, which occurs after all the rows have been properly allocated - There is less communication between the database and the client, so there is less network latency
- PostgreSQL includes optimizations for
COPYthat would not be available throughINSERT
Similar to the data exporting process discussed in the previous section, for data importing, the COPY command runs on the server and the \COPY command runs on the user workstation.
Here is an example of using the \COPY command to copy rows into a table from a file on the local machine:
- First, run the following SQL to create...