I’m developing Pg/PLSQL function for PostgresQL 9.1. When I use variables in a SQL query, optimizer build a bad execution plan. But if I replace a variable by its value the plan is ok.
For instance:
v_param := 100;
select count(*)
into result
from <some tables>
where <some conditions>
and id = v_param
performed in 3s
and
select count(*)
into result
from <some tables>
where <some conditions>
and id = 100
performed in 300ms
In first case optimizer generate a fixed plan for any value of v_param.
In second case optimizer generate a plan based on specified value and it’s significantly more efficient despite not using plan caching.
Is it possible to make optimizer to generate plan without dynamic binding and generate a plan every time when I execute the query?
This has been dramatically improved by Tom Lane in the just-released PostgreSQL 9.2; see What’s new in PostgreSQL 9.2 particularly:
This has been a long-standing and painful wart that’s previously required
SET enable_...params, the use of wrapper functions usingEXECUTE, or other ugly hacks. Now it should “just work”.Upgrade.
For anyone else reading this, you can tell if this problem is biting you because
auto_explainplans of parameterised / prepared queries will differ from those you get when youexplainthe query yourself. To verify, tryPREPARE ... SELECTthenEXPLAIN EXECUTEand see if you get a different plan toEXPLAIN SELECT.See also this prior answer.