4

I have a set of tables (about 100) in schema named qgep and which names start with vl_. They have all the same columns (colA, colB, colC).

What I'd like to do is to get one big table which is the union of all my vl_* tables, with also a column with the name of the original table.

I could get the list of the tables:

SELECT table_name
  FROM information_schema.tables 
  WHERE table_schema = 'qgep' 
  AND table_name LIKE 'vl_%'

The only way I found to solve my problem is to generate a SQL command to execute it further:

SELECT
  string_agg(
    'SELECT '''
    ||table_name
    ||''' AS table_name, colA, colB, colC FROM qgep.'
    ||table_name
  , ' UNION ')::text 
FROM information_schema.tables 
  WHERE table_schema = 'qgep' 
  AND table_name LIKE 'vl_%'"

Then executing this SQL command will output what I want. Although, it is very not performant, and quite ugly...

I would like to avoid using EXECUTE. Do you have any advice what to look for? Is there something I could do using WITH ... UNION ALL?

Would inheritance help me? Is it possible to know from which class is the record in the select?

5
  • They have all the same columns (colA, colB, colC). Add a column col_X to all of them, all with a different value, and combine the tables into one big table. Commented Mar 20, 2015 at 10:59
  • 1
    dynamic sql works with execute only (or in shell script :) Commented Mar 20, 2015 at 11:26
  • I am using this in a script. Anyway, I was hoping to find a nicer way. And maybe learn a bit. Commented Mar 20, 2015 at 12:47
  • Why do you have 100 tables you want to query all at once? Commented Mar 20, 2015 at 13:03
  • each table lists possible options for value list (selection combobox), and options are listed in several languages. I would like to generate one big table to use as a dicitonary. Commented Mar 20, 2015 at 13:07

2 Answers 2

5
create or replace function uall() returns table ( code integer ,
  value character varying(50),
  active boolean,tablename text ) AS $$ 
declare
  _i int;
  _r record;
  _t text := '';
begin 
  select distinct string_agg($s$select *,'$s$||table_name||$s$' from $s$||table_name,' union all ') into _t from information_schema.tables where table_name like 'vl_%';
return query execute _t;
end;$$ language plpgsql
;

select * from uall()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your help. I wanted to avoid using execute. I finally found the solution using inheritance.
3

The solution was indeed to use inheritance, and I finally found the solution on the Postgres doc.

SELECT p.relname, vl.* 
FROM qgep.is_value_list_base vl, pg_class p 
WHERE vl.tableoid = p.oid;

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.