HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Using Postgres COPY TO for data export without overwriting file

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withoutfilepostgresoverwritingforusingexportdatacopy

Problem

I'm running several queries with a script and psql. I am also exporting the results to a.csv using the COPY TO command. However, this overwrites the file a.csv when I would like to instead append the results to a.csv instead.

Is it possible using the COPY TO syntax perhaps there is some parameter I am missing? Or should I look at using other tools?

Solution

You could use the meta command \copy in psql (which encapsulates SQL COPY) on the command line, send it to stdout and and redirect output to be appended to a file - with >> instead of >:

psql -c '\copy (SELECT 1, 2) to stdout' >> /path/to/file_to_append_to.csv


(You probably need more connection parameters.)

You can use SQL COPY as well:

psql -c 'COPY (SELECT 1, 2) TO STDOUT' >> /path/to/file_to_append_to.csv


But it's often more convenient to use \copy instead because (quoting the manual):


file accessibility and access rights depend on the client rather than
the server when \copy is used.

Or, like Abelisto commented, from inside psql or any other client - if the program cat is available (basically on all *nix OS):

COPY (SELECT 1, 2) TO PROGRAM 'cat >> /path/to/file_to_append_to.csv'


Or, still from inside psql, on any system, you can set the current directory and an output file with:

\cd /path/to/
\o file_to_append_to.csv


The file gets created (only) if it does not exist yet.

Then you can also SQL COPY (or still \copy as well):

COPY (SELECT 1, 2) TO STDOUT;


The output is appended to the file.

Code Snippets

psql -c '\copy (SELECT 1, 2) to stdout' >> /path/to/file_to_append_to.csv
psql -c 'COPY (SELECT 1, 2) TO STDOUT' >> /path/to/file_to_append_to.csv
COPY (SELECT 1, 2) TO PROGRAM 'cat >> /path/to/file_to_append_to.csv'
\cd /path/to/
\o file_to_append_to.csv
COPY (SELECT 1, 2) TO STDOUT;

Context

StackExchange Database Administrators Q#167075, answer score: 9

Revisions (0)

No revisions yet.