Insert data using COPY

suggest change

COPY is PostgreSQL’s bulk-insert mechanism. It’s a convenient way to transfer data between files and tables, but it’s also far faster than INSERT when adding more than a few thousand rows at a time.

Let’s begin by creating a sample data file.

cat > sample_data.csv

1,Yogesh
2,Raunak
3,Varun
4,Kamal
5,Hari
6,Amit

And we need a two-column table to import this data into.

CREATE TABLE copy_test(id int, name varchar(8));

Now the actual copy operation, this will create six records in the table.

COPY copy_test FROM '/path/to/file/sample_data.csv' DELIMITER ',';

Instead of using a file on disk, you can insert data from stdin. The prompts below are from psql. Server-side COPY reads and writes files on the database server; the role needs permission to do that.

COPY copy_test FROM stdin DELIMITER ',';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 7,Amol
>> 8,Amar
>> \.
Time: 85254.306 ms

SELECT * FROM copy_test ;
 id |  name
----+--------
  1 | Yogesh
  3 | Varun
  5 | Hari
  7 | Amol
  2 | Raunak
  4 | Kamal
  6 | Amit
  8 | Amar

You can also copy data from a table to a file:

COPY copy_test TO 'path/to/file/sample_data.csv'  DELIMITER ',';

For more details on COPY you can check here

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents