Prepared Statements Switch To Generic Plans
After five EXECUTEs the planner may switch a prepared statement from custom to generic plans; pg_prepared_statements exposes the counters.
Code
-- 服务端预编译语句:PREPARE 之后反复 EXECUTE,省去重复解析
CREATE TEMP TABLE accounts (id bigint PRIMARY KEY, balance_cents integer NOT NULL);
INSERT INTO accounts SELECT g, g * 100 FROM generate_series(1, 100) g;
PREPARE account_balance (bigint) AS
SELECT id, balance_cents FROM accounts WHERE id = $1;
-- 前 5 次走 custom plan:字面值代入 $1,可用列统计精确估行
EXECUTE account_balance(7);
EXECUTE account_balance(7);
EXECUTE account_balance(7);
EXECUTE account_balance(7);
EXECUTE account_balance(7);
-- 第 6 次起考虑切换 generic plan:$1 不再内联,一条计划服务所有参数
EXECUTE account_balance(7);
EXECUTE account_balance(7);
SELECT name, custom_plans, generic_plans
FROM pg_prepared_statements
WHERE name = 'account_balance';
DEALLOCATE account_balance; -- 显式释放;会话结束同样自动清理Custom plans first
The first five EXECUTEs inline the literal into a custom plan where column statistics give precise row estimates. The snippet runs exactly five so the demo can observe the switch.
The generic switch
From the sixth execution the planner may switch to a generic plan where $1 is no longer inlined and one plan serves all parameter values. pg_prepared_statements exposes the counters: custom_plans and generic_plans show which side absorbed each execution.
Lifecycle
DEALLOCATE account_balance releases the statement explicitly; the session end would clean it up too, since prepared statements are session-scoped objects (the demo table is a TEMP table for the same reason).
Interactive Tools for This Topic
FAQ
- When does a prepared statement consider the generic plan?
- After five executions with custom plans; from the sixth the planner may switch, which pg_prepared_statements makes visible through its plan counters.
- Why is DEALLOCATE shown in the demo?
- To close the lifecycle explicitly; prepared statements live for the session, and DEALLOCATE frees the plan without waiting for session end.
Report a problem with this exampleOpens a pre-filled issue on GitHub.