Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dyanmic Table name in Postgres query

Tags:

postgresql

Is there any way to replace the table name in a query with value stored in another table ? This is in postgres sql

Eg

Meta_table

col1    | col 2
Table 1 | val1
Table 2 | val2

My requirement

select * 
from (select col1 from meta_table where col2 = val2)
like image 685
bottle avi Avatar asked May 09 '26 10:05

bottle avi


1 Answers

Probably the most flexible and efficient way is dynamically creating a temporary view using function:

create or replace function f_prepare(tname text, vname text) returns text language plpgsql as $$
begin
    execute format(
        'create or replace temporary view %I as select * from %I',
        vname, tname);
    return vname;
end $$;

Then you can use the created view in usual way, for example;

select f_prepare('pg_class', 'v_class');
select * from v_class where relname = 'pg_database'; -- Index on the source table will be used here

and using your code:

select f_prepare((select col1 from meta_table where col2 = 'val2'), 'v');
select * from v;

And as any other temporary objects, created views will not conflict with other sessions and will be dropped on disconnect.

like image 177
Abelisto Avatar answered May 12 '26 05:05

Abelisto