skip to content

prepared statements and generic plans

five custom plans, then maybe one generic plan forever. plan_cache_mode, explained.

address
everything.optimizer.generic_plans
part
part 10, the optimizer
chapter
chapter 8 of 10
reading time
7 min

a prepared statement is parsed once and planned at execution. for its first five executions postgres makes a custom plan for the actual parameter values. after that it also prices a generic plan, made for any value ($1 in EXPLAIN), and if that costs no more than the custom plans did on average, it uses the generic one from then on, without planning again.

usually a good deal. on skewed data it isn't, and plan_cache_mode lets you choose.

the picture

you know how a query can be fast in psql and slow from the app, same SQL, same values? the app is often using a prepared statement (most drivers do, through the extended protocol), and it might be running a plan that was made for no value in particular.

think of a tailor. the first five customers get a suit made to measure. by then the tailor knows roughly what people cost to fit, and makes one off-the-rack suit in an average size. if that suit is cheaper than the made-to-measure ones were on average, from now on everybody gets the rack suit, whatever their size. fine for most people. bad for the very tall.

here's that, with events.kind, where 'view' is 60% of the rows and 'signup' is 2%:

#EXECUTE by_kind(…)planconditionest. rowstotal cost
1'view'custom Seq Scan(kind = 'view')15,112685.29
2'view'custom Seq Scan(kind = 'view')15,112685.29
3'view'custom Seq Scan(kind = 'view')15,112685.29
4'view'custom Seq Scan(kind = 'view')15,112685.29
5'view'custom Seq Scan(kind = 'view')15,112685.29
6'view'generic Bitmap Scan(kind = $1)5,000469.05
7'signup'generic Bitmap Scan(kind = $1)5,000469.05
8'purchase'generic Bitmap Scan(kind = $1)5,000469.05
real output, postgres 18.6 (PGlite 0.5.12) · plan-cache
eight executions of one prepared statement, five with 'view' and then three others. executions 1 to 5 are custom plans for 'view': seq scans. at execution 6 postgres prices the generic plan (estimated for 5,000 rows, any kind), finds it cheaper than the custom average, and keeps it, for 'signup' and 'purchase' too. the condition says $1: the value isn't in the plan.

five custom plans

sqldb=events · session pc
CREATE INDEX events_kind ON events (kind);
ANALYZE events;
PREPARE by_kind(text) AS
  SELECT max(occurred_at) FROM events WHERE kind = $1;
EXPLAIN EXECUTE by_kind('signup');
EXPLAIN EXECUTE by_kind('view');
SELECT name, generic_plans, custom_plans FROM pg_prepared_statements;
output, from postgres 18.6
#1 · CREATE INDEX
#2 · ANALYZE
#3 · PREPARE
#4 · EXPLAIN
Aggregate (cost=366.73..366.74 rows=1 width=8) -> Bitmap Heap Scan on events (cost=8.16..365.48 rows=500 width=8) Recheck Cond: (kind = 'signup'::text) -> Bitmap Index Scan on events_kind (cost=0.00..8.04 rows=500 width=0) Index Cond: (kind = 'signup'::text)
#5 · EXPLAIN
Aggregate (cost=685.28..685.29 rows=1 width=8) -> Seq Scan on events (cost=0.00..647.50 rows=15112 width=8) Filter: (kind = 'view'::text)
#6 · SELECT 1
nametextgeneric_plansint8custom_plansint8
by_kind02
(1 row)

two executions, two custom plans, each made for its value: a bitmap scan for the 500 signups, a seq scan for the 15,112 views. the value is in the plan as a constant ('signup'::text). pg_prepared_statements counts which kind of plan each execution got. (EXPLAIN EXECUTE goes through the plan cache exactly like EXECUTE, so it counts.)

then, maybe, a generic plan

the generic plan is planned with $1 unknown. the estimate for kind = $1 can't use the MCV list, because it doesn't know which value: it uses 1 / n_distinct, so 1/5 of 25,000 = 5,000 rows, for any kind (estimating rows). at the sixth execution postgres compares:

  • the average cost of the custom plans so far, plus an estimate of what planning each of them cost (1,000 × cpu_operator_cost per table in the query, plus one more), since a generic plan saves that every time,
  • the generic plan's cost.

if the generic plan is no more expensive, it wins and is cached. in the figure, the custom plans averaged 685.29 and the generic plan costs 469.05, so from execution 6 on everyone gets the bitmap scan built for 5,000 rows.

sqldb=events · session pc
continues session pc (1 earlier block run first)
EXECUTE by_kind('view');
EXECUTE by_kind('view');
EXECUTE by_kind('view');
EXPLAIN EXECUTE by_kind('signup');
SELECT name, generic_plans, custom_plans FROM pg_prepared_statements;
output, from postgres 18.6
#1 · SELECT 1
maxtimestamptz
2026-05-31 23:55:12+00
(1 row)
#2 · SELECT 1
maxtimestamptz
2026-05-31 23:55:12+00
(1 row)
#3 · SELECT 1
maxtimestamptz
2026-05-31 23:55:12+00
(1 row)
#4 · EXPLAIN
Aggregate (cost=469.04..469.05 rows=1 width=8) -> Bitmap Heap Scan on events (cost=59.04..456.54 rows=5000 width=8) Recheck Cond: (kind = $1) -> Bitmap Index Scan on events_kind (cost=0.00..57.79 rows=5000 width=0) Index Cond: (kind = $1)
#5 · SELECT 1
nametextgeneric_plansint8custom_plansint8
by_kind15
(1 row)

there it is: Recheck Cond: (kind = $1). this is the plan for every execution from now on, until the statement is deallocated, the session ends, or something invalidates the cache (an ANALYZE or DDL on the table).

predict the output
the first five executions were all 'signup' (500 rows, cheap bitmap scans). what does execution six use?
sql
EXECUTE by_kind('signup');  -- × 5, then once more

when the generic plan is wrong

the bad case is the one in the figure, seen from the other side: a common value made the custom plans expensive, so the generic plan looked like a bargain. now run 'view' itself on that cached plan:

plan_cache_mode =
query.sql
  1. 1SET plan_cache_mode = auto;
  2. 2EXECUTE by_kind('view');
the result for auto
countint8
15112
(1 row)
the plan

plan_cache_mode = auto: the cached generic plan, run for 'view'. it was priced for 5,000 rows and gets 15,112.

real output, postgres 18.6 (PGlite 0.5.12) · plan-cache
EXECUTE by_kind('view') under each plan_cache_mode, run for real. auto (after the five executions above) and force_generic_plan use the generic bitmap scan, estimated at 5,000 rows, getting 15,112. force_custom_plan plans for 'view' every time and gets the seq scan the data wants.

a bitmap scan for 60% of the table, priced for 20% of it. here that's a modest loss; with a nested loop or a join order chosen on that estimate, it's the "fast in psql, slow in the app" query. the shape to look for: a column with a few very common values and many rare ones, used as a parameter.

plan_cache_mode

sqldb=events · session pc
continues session pc (2 earlier blocks run first)
SET plan_cache_mode = force_custom_plan;
EXPLAIN EXECUTE by_kind('view');
RESET plan_cache_mode;
output, from postgres 18.6
#1 · SET
#2 · EXPLAIN
Aggregate (cost=685.28..685.29 rows=1 width=8) -> Seq Scan on events (cost=0.00..647.50 rows=15112 width=8) Filter: (kind = 'view'::text)
#3 · RESET

three settings (postgres 12+):

  • auto (default): five custom plans, then the generic one if it's not more expensive.
  • force_custom_plan: plan every execution for its values. you pay planning time each time, and never get a plan for the wrong value.
  • force_generic_plan: use the generic plan from the first execution. no planning after the first, and every value shares one plan.

set it per session, per role or database, or per function with SET in its definition, rather than server-wide:

sql
ALTER ROLE app SET plan_cache_mode = force_custom_plan;

a short, simple query with a uniform parameter is the generic plan's best case; a query on a skewed column is custom's.

keylines

  • prepared statements are planned at execution: five custom plans first, for the actual values.
  • then a generic plan, planned for $1, is used if it costs no more than the custom average (planning included).
  • a generic plan's estimate ignores the value: 1 / n_distinct for =, so skewed columns suffer.
  • EXPLAIN EXECUTE shows which you got: $1 in the plan means generic.
  • plan_cache_mode: auto, force_custom_plan, force_generic_plan. set it per role or function.