wernerfeuer
wernerfeuer

Reputation: 49

Export from PostgreSQL multiple times to same file

Is it possible to export a table to csv, but to append multiple selections to the same file?

I would like to export (for instance):

SELECT * FROM TABLE WHERE a > 5

Then, later:

SELECT * FROM TABLE WHERE b > 2

This must go to the same file.

Thanks in advance!

Upvotes: 0

Views: 2687

Answers (3)

Michael Rush
Michael Rush

Reputation: 4340

Using \o in combination with \copy to STDOUT seems to work. For example:

db=> \o /tmp/test.csv
db=> \copy (select 'foo','bar') to STDOUT with CSV;
db=> \copy (select 'foo','bar') to STDOUT with CSV;
db=> \q

$ cat /tmp/test.csv 
foo,bar
foo,bar

Upvotes: 0

fiskeben
fiskeben

Reputation: 3467

Use \o <filename> to output to a file. All your SELECT statements after using \o will be appended to <file> until you set \o to something else.

Upvotes: 1

Scott S
Scott S

Reputation: 72

The only way that I know of to do this is from the command-line, redirecting output.

psql -d dbname -t -A -F"," -c "SELECT * FROM TABLE WHERE a > 5" >> output.csv

then later

psql -d dbname -t -A -F"," -c "SELECT * FROM TABLE WHERE b > 2" >> output.csv

You can look up the command line options here.

http://www.postgresql.org/docs/9.0/static/app-psql.html

Upvotes: 1

Related Questions