CYBERTEC PostgreSQL Blog· Laurenz Albe·· 14d ago
How to Stabilize Query Plans in PostgreSQL 19 with pg_stash_advice
Plan stability with pg_stash_advice: how to do it in practice
Key Takeaway
PostgreSQL 19 uses pg_plan_advice and pg_stash_advice to constrain join order without rewriting SQL. In the example, a row estimate of 20 versus 990 led to a 405.646 ms query. Stored advice survives restarts but not pg_upgrade. cybertec-postgresql.com/en/pg…
Why It Matters
Constraining only the join order can guard against a bad choice caused by underestimated row counts while leaving the planner free to adapt join methods and scan strategies.
Technical Breakdown · Distilled from the original source
Why the planner underestimates the goods count
- The test uses three
UNLOGGEDtables with 1,980 goods and 5 million orders, withshared_bufferssized to cache all the data. ACME accounts for 990 goods, while each other producer accounts for 10. Orders are evenly distributed across goods and customers. - The planner knows that
producer_id = 1accounts for half the goods, but it cannot resolve that ID fromproducer_nameat planning time. It falls back to an average, estimating 20 rows instead of the actual 990. The nested loop scans each of the two order indexes 990 times.
Constrain join order without fixing the entire plan
- The example starts with
ordersfiltered by customer and constrains only the join order, not the join method or scan strategy. Settingpg_stash_advice.stash_nameat database level activates the stash only for new connections. - Stashes live in shared memory and are periodically saved to
pg_stash_advice.tsvby default for reload on restart.pg_dumpdoes not export them, sopg_upgradedoes not carry them over.
Alternatives to fixing the plan
- Setting
random_page_costto1.1also yields a good plan in the example. Another option is to look up the producer ID before querying goods and orders. The second query uses a hash join and takes 1.483 ms, but splitting the query requires an application change and an extra database round trip.
Source: CYBERTEC PostgreSQL Blog· cybertec-postgresql.com
PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.