patternsqlMinor
Using Postgres COPY TO for data export without overwriting file
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?
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
(You probably need more connection parameters.)
You can use SQL
But it's often more convenient to use
file accessibility and access rights depend on the client rather than
the server when
Or, like Abelisto commented, from inside psql or any other client - if the program
Or, still from inside psql, on any system, you can set the current directory and an output file with:
The file gets created (only) if it does not exist yet.
Then you can also SQL
The output is appended to the file.
\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.csvBut 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.csvThe 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.csvpsql -c 'COPY (SELECT 1, 2) TO STDOUT' >> /path/to/file_to_append_to.csvCOPY (SELECT 1, 2) TO PROGRAM 'cat >> /path/to/file_to_append_to.csv'\cd /path/to/
\o file_to_append_to.csvCOPY (SELECT 1, 2) TO STDOUT;Context
StackExchange Database Administrators Q#167075, answer score: 9
Revisions (0)
No revisions yet.