1

Is it possible to copy multiple postgresql queries into single csv file? As of now am copying single query into csv file as

copy (select * from table1) to 'file.csv' with csv header;

Now i want to copy 2 query result together . Is that possible ? something like,

copy (select * from table1,select name from table2) to 'file.csv' with csv header

Any help?

1 Answer 1

3

You can:

copy (select 'table1' as table_id, * from table1
      UNION ALL
      select 'table2' as table_id, * from table2)
 to 'file.csv' with csv header

If tables have identical structure.

Or you can:

copy (select field1, field2, null, null from table1
      UNION ALL
      select null,null, field3, field4 from table2)
 to 'file.csv' with csv header

If tables don't have identical structure.

The problem is - COPY ... FROM can only work with tables (details here).

So you will need to: CREATE TEMP TABLE tmp_copy_tbl, COPY tmp_copy_tbl FROM and then INSERT ... SELECT ... FROM tmp_copy_tbl

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

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.