Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting results from multiple sql queries in postgresql

I have postgresql-9.2 installed on my local machine (running windows 7) and I am also the administrator. I am using the Query Tool of pgAdmin III to query my database. My problem is as follows:

Say I have two tables Table_A and Table_B with different number of columns. Also, say I have following two very simple queries:

select * from Table_A;
select * from Table_B;

I want to run both these queries and see the output from both of them together. I dont mind if I see the output in the GUI or in a file.

I also tried the copy command and outputting to a csv. But instead of appending to the file it overwrites it. So, I always end up with the results from query 2 only. The same thing happens with the GUI.

It is really annoying to comment one query, run the another, output to two different files and then merge those two files together.

like image 969
PS1 Avatar asked Jun 09 '13 10:06

PS1


2 Answers

This is not currently supported by PostgreSQL - from the docs (http://www.postgresql.org/docs/9.4/interactive/libpq-exec.html):

The command string can include multiple SQL commands (separated by semicolons). Multiple queries sent in a single PQexec call are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands included in the query string to divide it into multiple transactions. Note however that the returned PGresult structure describes only the result of the last command executed from the string. Should one of the commands fail, processing of the string stops with it and the returned PGresult describes the error condition.

like image 56
Ibrahim Dauda Avatar answered Oct 13 '22 03:10

Ibrahim Dauda


Your problem does not depend on the client.

Assuming all columns to be of type text, try this query:

SELECT col_a AS col_ac, col_b AS col_bd
      ,NULL::text AS col_e, NULL::text AS col_f
FROM   table_a

UNION  ALL
SELECT col_c, col_d, col_e, col_f
FROM   table_b;

Column names and data tapes are defined by the first branch of a UNION SELECT. The rest has to fall in line.

like image 22
Erwin Brandstetter Avatar answered Oct 13 '22 03:10

Erwin Brandstetter