Dynamic Commands in PL/pgSQL
The execute keyword allows you to run a dynamic command - where perhaps a table or column name is not known ahead of time.
1create or replace function get_row_count(table_name text)2 returns integer3 as $$4declare5 c int;6begin7 execute format('select count(*) from %I', table_name) into c;8
9 return c;10end;11$$ language plpgsql;12
13create table s (id serial primary key);14insert into s default values;15
16create table t (id serial primary key);17insert into t default values;18insert into t default values;19
20select get_row_count('s'); -- 121select get_row_count('t'); -- 2Some notes from the docs:
- There is no plan caching for dynamic commands - commands executed via
execute. - Be careful not to do something like
key = null, wherenullis passed in dynamically. (Useis distinct from). - See the
usingclause for passing parameters to the dynamic command.
You can read more about this here.