2

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;
1
  • That's not the error. THat's debug info. The error is probably on the preceding line in the logs or output. Commented Oct 3, 2017 at 6:44

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

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.