Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between copy and \copy commands in postgresql

Tags:

postgresql

To transfer data between a file and a table in postgresql there are two options

COPY my_table FROM '/Users/user/Downloads/test.csv' DELIMITER ',' CSV HEADER;

Or

\COPY my_table FROM '/Users/user/Downloads/test.csv' DELIMITER ',' CSV HEADER;

My question is what is the difference between the two and which one is faster?

like image 256
Apurv Agarwal Avatar asked Aug 04 '18 02:08

Apurv Agarwal


People also ask

What is copy command in Postgres?

The PostgreSQL \copy command is a meta-command available from the psql interactive client tool. You can use \copy to import data into a table on your RDS for PostgreSQL DB instance.

Does COPY overwrite Postgres?

If you COPY data into a table already containing data, the new data will be appended. If you COPY TO a file already containing data, the existing data will be overwritten.

How do I COPY output from PostgreSQL?

The easiest but the most efficient way to export data from a Postgres table to a CSV file is by using the COPY command. COPY command generates a CSV file on the Database Server. You can export the entire table or the results of a query to a CSV file with the COPY TO command.

How do I COPY a table in PostgreSQL?

To copy a table with partial data from an existing table, users can use the following statement: Syntax: CREATE TABLE new_table AS SELECT * FROM existing_table WHERE condition; The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table.


1 Answers

The COPY command is executed fully on server side - input/output is related to server side streams. But these streams can be redirected to client side - when you run COPY in a pre-configured environment. \COPY is this case.

\COPY is psql's commands - it can be executed only from psql and it prepares internal environment for a possible read/write from client side streams, and it execute COPY commands.

So difference between COPY and \COPY is minimal. \COPY is COPY executed in different configuration for a possible read/write data from client. The performance should be same - \COPY can be a little bit slower due to network overhead (it is clear), but it should not be significant. In this case the communication protocol should be effective.

like image 105
Pavel Stehule Avatar answered Sep 28 '22 01:09

Pavel Stehule