Video in progress
A prepared statement suddenly got slow after it had run 5-6 times. What could be the cause?
Postgres plans a prepared statement with a custom plan (based on the actual parameters) for the first 5 runs, then switches to a generic plan if its cost looks similar. If the parameter values are unevenly distributed, the generic plan can be very bad for some values.
📖 Answer
The situation: in the status column, 99% is DONE and 1% is NEW. The query is WHERE status = $1.
- A custom plan uses an index scan for
$1 = 'NEW'and a seq scan for$1 = 'DONE'. Both are right. - A generic plan doesn't know the value, takes the average selectivity and picks a single plan. That may turn into a seq scan for
NEW.
On the Java side this looks even more confusing: PgJDBC first sends an unnamed statement (a custom plan every time), and switches to a named server-side statement only after reaching prepareThreshold=5. The server then builds 5 more custom plans for that named statement. So the application shows a strange symptom: "slow from about the 9th-10th call".
Checking:
PREPARE q(text) AS SELECT * FROM job WHERE status = $1;
EXPLAIN EXECUTE q('NEW'); -- run it 6-7 times and watch the plan change
Since PG16 there is also EXPLAIN (GENERIC_PLAN).
The solutions:
- PG12+:
SET plan_cache_mode = force_custom_plan, at the session or role level, or in a separate connection setting just for this query; - add a partial index (
WHERE status = 'NEW') and use a literal in the query; prepareThreshold=0in the JDBC URL turns off server-side prepare, but you pay the parse cost every time.
Often the best solution is to split the query in two: "new tasks" and "history" as separate queries, each with its own index.
Sign up to mark studied questions and save your progress.