Planning Is Not Free
Turning SQL into an execution plan means parsing, rewriting, and searching many possible join orders and access paths. For a query run thousands of times, repeating this is wasteful. A plan cache stores the compiled plan keyed by the query shape.
Parameterized Plans
To reuse plans across different values, engines use parameterized or prepared statements where literal values become placeholders. The same plan then serves many parameter sets.
- A prepared statement is planned once and executed many times.
- The cache is keyed by normalized query text or a statement handle.
The Parameter Sniffing Trap
A cached plan was chosen for the values seen at planning time. If those values are unusual, the plan may be skewed for later values with different data distribution. Engines mitigate this with generic versus custom plan choices and by replanning when estimates drift far from reality.
Key idea
A plan cache reuses compiled plans for repeated parameterized queries to skip planning, but a plan chosen for one parameter set can be skewed for others, so engines sometimes replan.