Reputation: 632
I am trying to do an intersect of a select statement with an array that is dynamically computed in a loop and then measure the time taken for each of those intersect queries.
So in the first iteration of the loop, I want the query to be like this:
'select sub_id from table where main_id=1 INTERSECT select array[''80'']';
In the second iteration:
'select sub_id from table where main_id=1 INTERSECT select array[''80'', ''81'']';
and so on and measure the time taken in each of those iterations to execute the query.
When I run this script, I get the error:
CONTEXT: PL/pgSQL function inline_code_block at assignment
which corresponds to the line where I initialize query1. How do I correct the assignment to the query1? I am using PostgreSQL 9.1.
arr := '{}';
for j in 80..120 loop
arr := array_append(arr, j::text);
query1 := 'select sub_id from table where main_id=1 INTERSECT' || ' select unnest(arr)';
execute 'explain (analyse, format json) ' || query1 into p;
t := (p->0->>'Planning Time')::float + (p->0->>'Execution Time')::float;
total_time := total_time + t;
end loop;
Upvotes: 2
Views: 723
Reputation: 238086
The query text you execute
can't reference variables from the calling scope. You have to pass the variable as a parameter with using
like:
query1 := 'select sub_id from YourTable where main_id=1 INTERSECT select unnest($1)';
execute 'explain (analyse, format json) ' || query1 using arr into p;
^^^^^^^^^
Working example at rextester.com
Upvotes: 3