How to store the result of all of the queries below into one CSV file in PostgreSQL by executing one COPY (......) to.... statement.

select id,name from first;
select id,salary,father_name from second;
select id,score,bonus,extra from third;

1 Answer 1


far as i know not possible if you want append one table after another to same file. But you can get them to same file using union


select f.id as fid , null sid   from first f union select null fid , s.id sid from second s

that would create file where all data from first table are 1;null 2;null .... and second table null;1 null;2

or you can use psql command line tool in linux and call :

psql mydb -c "select id,name from first; " >> myOutFile.txt
psql mydb -c "select id,salary,father_name from second; " >> myOutFile.txt
psql mydb -c "select id,score,bonus,extra from third; " >> myOutFile.txt

In *nix, the > (greater than) character operator redirects output to a file, overwriting the file.

When doubled, the >> operator redirects output to a file appending the redirected output at the end.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.