0

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!

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.