PostgreSQL's COPY and \COPY

PostgreSQL is equivalent to a Swiss Army Knife in the database world. There are things in PostgreSQL that are very simple to use, while in another database, they take many more steps to accomplish. But sometimes, the knife has too many blades, which can cause confusion. This is one of those cases.

COPY and \COPY

I needed a quick dump of a table as part of an ETL (Extract, Transform, and Load - official definition, Exorcism, Trauma, and Lost-sleep - unofficially) to port some data. The COPY command is a quick way to output and write the data to a file.  The two copy commands below illustrate adding a delimiter and then writing the output to a table.

demo=# select * from z;
 a | b  |  c  
---+----+-----
 1 | 10 | 100
 2 | 20 | 200
 3 | 30 | 300
 4 | 40 | 400
(4 rows)
demo=# copy z to stdout (DELIMITER ',');
1,10,100
2,20,200
3,30,300
4,40,400
demo=# copy z to '/tmp/z' (DELIMITER ',');
COPY 4
demo=# 

The trick is that you must REMEMBER that the PostgreSQL server is writing the file and will need permission to write in the desired directory. If you try to write your current directory, you will probably see this:

demo=# copy z to 'z' (DELIMITER ',');
ERROR:  relative path not allowed for COPY to file
demo=# 

ETL

The table I needed to 'fix' as part of the ETL process was edited and was now ready to load. I created a new table.

demo=# create table zz (a1 int, b1 int, c1 int);
CREATE TABLE

The tricky part is that you can not use COPY to load the data. You need to use psql's \COPY! Consider \COPY a wrapper on the client side around the server's COPY command.

demo-# \copy zz from '/tmp/z/' (delimiter ',');
COPY 4
demo-# 

I find the COPY - /COPY pairing very handy.

More?


I highly recommend Wager Bianchi's COPY vs. \copy in PostgreSQL and their Security Implications for DBAs for those seeking more information on this subject and its healthy warning about security issues.


Comments

Popular posts from this blog

Can Artificial Intelligence Created Better Tables Than You?

How PostgreSQL's Aggregate FILTER Will Spoil You