Because explain cannot be used, for example, for example. a SELECT is a bit complicated, and for that you need dynamic SQL.
The following worked for me:
do $$ declare plan_line record; begin for plan_line in execute 'explain select * from public.some_table where 1=2' loop insert into plans values (plan_line."QUERY PLAN"); end loop; end; $$
Having an instruction to be explained in a line makes things a little more complicated.
If I needed this regularly, I would probably create a function that does this:
create or replace function explain(to_explain text) returns setof text as $$ declare plan_line record; begin for plan_line in execute 'explain '||to_explain loop return next plan_line."QUERY PLAN"; end loop; end; $$ language plpgsql;
Then you can do something like:
insert into plans select * from explain('select ...');
source share