Skip to content
dbexplore

PostgreSQL 19

Plan advice in PostgreSQL 19

For anyone who has lost an afternoon to a plan that flipped and wants to know whether pinning it in 19 is the fix.

Reference page, revised in place. Last updated .

Pin one query, and know what the pin covers

PostgreSQL 19 ships two modules that let you describe and constrain the plan the planner picks. pg_plan_advice reads a short advice string from a setting and steers whichever session sets it. pg_stash_advice stores advice against a query identifier and applies it to every session that names the stash. Our view is that this is a scalpel for the one query that keeps flipping, and a poor fleet policy. A stashed pin applies to every statement that hashes to the same identifier, which means every constant value and, since PostgreSQL 18, the same-named table in another schema. It also goes stale without telling anyone.

Both modules are recorded under Additional Modules in the PostgreSQL 19 release notes. The pg_plan_advice reference opens with its own warning that overriding the planner can easily backfire when the data changes, and most of this page is a worked example of that sentence.

Nothing to load on 18

LOAD 'pg_plan_advice';
ERROR:  could not access file "pg_plan_advice": No such file or directory

Before 19 the options shipped with PostgreSQL were the blunt ones: cost settings, the enable_* switches, and fixing the statistics. The usual answer before 19 was pg_hint_plan, a third-party extension that reads hints from comments in the query text or, with pg_hint_plan.enable_hint_table on, from a hint_plan.hints table keyed by query identifier, so it too can steer a query without editing it. The differences are that these modules ship with PostgreSQL, and that pg_plan_advice works by ruling plans out and reports, line by line in EXPLAIN, whether each piece of advice matched and was followed. The blunt options remain the better first move, and query plan regression walks through them in the order we would try them.

Reading the advice for a plan you like

The fixture is a shipping table where one state is rare: two consignments in a hundred are held, the rest delivered, with an index on the state. The module is loaded per session with LOAD here; in production it would go in shared_preload_libraries or session_preload_libraries, and each block below is its own session, which is why the LOAD repeats.

CREATE TABLE depots (depot_id int PRIMARY KEY, name text, zone text);
CREATE TABLE consignments (consignment_id bigint PRIMARY KEY, depot_id int, state text, booked_at timestamptz);
INSERT INTO depots SELECT g, 'depot ' || g, CASE WHEN g % 10 = 0 THEN 'north' ELSE 'south' END
FROM generate_series(1, 200) AS g;
INSERT INTO consignments
SELECT g, 1 + g % 200, CASE WHEN g % 50 = 0 THEN 'held' ELSE 'delivered' END,
       timestamptz '2026-11-01' + g * interval '1 second'
FROM generate_series(1, 300000) AS g;
CREATE INDEX consignments_state ON consignments (state);
ANALYZE depots, consignments;
CREATE TABLE
CREATE TABLE
INSERT 0 200
INSERT 0 300000
CREATE INDEX
ANALYZE

EXPLAIN (PLAN_ADVICE) writes the chosen plan back out as advice, one line for each decision in it that the module can control.

LOAD 'pg_plan_advice';
EXPLAIN (COSTS OFF, PLAN_ADVICE)
SELECT d.name, count(*)
FROM consignments c JOIN depots d USING (depot_id)
WHERE c.state = 'held' AND d.zone = 'north'
GROUP BY d.name;
LOAD
                            QUERY PLAN                             
-------------------------------------------------------------------
 HashAggregate
   Group Key: d.name
   ->  Hash Join
         Hash Cond: (c.depot_id = d.depot_id)
         ->  Index Scan using consignments_state on consignments c
               Index Cond: (state = 'held'::text)
         ->  Hash
               ->  Seq Scan on depots d
                     Filter: (zone = 'north'::text)
 Generated Plan Advice:
   JOIN_ORDER(c d)
   HASH_JOIN(d)
   SEQ_SCAN(d)
   INDEX_SCAN(c public.consignments_state)
   NO_GATHER(c d)
(15 rows)

Five lines, because this plan needed five decisions: the join order, the join method, a scan method for each table, and no parallelism. The full vocabulary is larger. The reference page also has tags for index-only, bitmap heap and TID scans, for excluding one of the alternative plan shapes the planner sometimes builds by copying part of the tree, for pushing a join down to a foreign server, for merge joins and the memoize and materialize forms of a nested loop, for partitionwise joins, for semijoin uniqueness, and for placing Gather or Gather Merge nodes. It has no tag at all for aggregation, whether by sorting or hashing or pushed below a join, and nothing about set operations such as UNION. There is also no way to force a plan the planner never considered, because the module works by ruling options out, and the reference page warns that under the genetic query optimizer, which takes over for queries joining many tables, join advice works only probabilistically.

What you leave out is free to move

The docs recommend trimming the generated string to only the decisions you need to enforce. Here is what that looks like when the two decisions are a sequential scan of the big table and a plain nested loop into the small one.

LOAD 'pg_plan_advice';
SET pg_plan_advice.advice = 'SEQ_SCAN(c) NESTED_LOOP_PLAIN(d)';
EXPLAIN (COSTS OFF)
SELECT d.name, count(*)
FROM consignments c JOIN depots d USING (depot_id)
WHERE c.state = 'held' AND d.zone = 'north'
GROUP BY d.name;
LOAD
SET
                            QUERY PLAN                             
-------------------------------------------------------------------
 Finalize GroupAggregate
   Group Key: d.name
   ->  Gather Merge
         Workers Planned: 1
         ->  Sort
               Sort Key: d.name
               ->  Nested Loop
                     ->  Partial HashAggregate
                           Group Key: c.depot_id
                           ->  Parallel Seq Scan on consignments c
                                 Filter: (state = 'held'::text)
                     ->  Index Scan using depots_pkey on depots d
                           Index Cond: (depot_id = c.depot_id)
                           Filter: (zone = 'north'::text)
 Supplied Plan Advice:
   SEQ_SCAN(c) /* matched */
   NESTED_LOOP_PLAIN(d) /* matched */
(17 rows)

Both pieces of advice matched and were obeyed, and the plan changed in two ways nobody asked for. The scan went parallel, because the advice said nothing about gathering, and the aggregation moved underneath the join, which no advice can say anything about. Neither is wrong here. Both are the planner doing its job in the space the advice left, and they are the parts of a pinned plan that will keep changing as the data does.

Our recommendation has a cost here. Trimming the advice to one decision is what lets the rest of the plan adapt; pinning the whole generated string freezes everything the module can express, which is the over-constraint the docs warn will go wrong when the distribution shifts. How much of the string to keep is a choice you make per query, between those two risks, and it deserves a written reason.

Advice that does not apply fails quietly

Advice never makes planning fail. By default, the feedback comment beside each line is the only sign that it did nothing. Advice that asks for something impossible can also leave plan nodes marked Disabled: true in EXPLAIN, and the reference page warns that such a plan can be much worse than no advice at all.

LOAD 'pg_plan_advice';
SET pg_plan_advice.advice = 'INDEX_SCAN(c consignments_by_state) HASH_JOIN(dd)';
EXPLAIN (COSTS OFF)
SELECT d.name, count(*)
FROM consignments c JOIN depots d USING (depot_id)
WHERE c.state = 'held' AND d.zone = 'north'
GROUP BY d.name;
LOAD
SET
                                QUERY PLAN                                 
---------------------------------------------------------------------------
 HashAggregate
   Group Key: d.name
   ->  Hash Join
         Hash Cond: (c.depot_id = d.depot_id)
         ->  Index Scan using consignments_state on consignments c
               Index Cond: (state = 'held'::text)
         ->  Hash
               ->  Seq Scan on depots d
                     Filter: (zone = 'north'::text)
 Supplied Plan Advice:
   INDEX_SCAN(c consignments_by_state) /* matched, inapplicable, failed */
   HASH_JOIN(dd) /* not matched */
(12 rows)

The index name is wrong and the alias dd does not exist in the query. The plan is the one the planner would have picked anyway, and the query would have run without a word. pg_plan_advice.feedback_warnings turns a failure like this into a warning, and it is off by default. We would turn it on in any session that sets advice, because the alternative is reading EXPLAIN output to find out whether a pin still holds.

A cached plan ignores the advice you just set

Advice is consulted only when a query is planned. Under the default plan_cache_mode of auto, the PREPARE reference says a prepared statement’s first five executions get custom plans, each planned afresh, so new advice takes effect there. After that the server may settle on a cached generic plan, and new advice is ignored until that plan is replaced. The block below forces the generic plan so the effect shows on the first execution instead of the sixth.

LOAD 'pg_plan_advice';
SET plan_cache_mode = force_generic_plan;
PREPARE held_for(text) AS SELECT count(*) FROM consignments WHERE state = $1;
EXPLAIN (COSTS OFF) EXECUTE held_for('held');
SET pg_plan_advice.advice = 'SEQ_SCAN(consignments) NO_GATHER(consignments)';
EXPLAIN (COSTS OFF) EXECUTE held_for('held');
DISCARD PLANS;
EXPLAIN (COSTS OFF) EXECUTE held_for('held');
LOAD
SET
PREPARE
                           QUERY PLAN                           
----------------------------------------------------------------
 Aggregate
   ->  Index Only Scan using consignments_state on consignments
         Index Cond: (state = $1)
(3 rows)

SET
                           QUERY PLAN                           
----------------------------------------------------------------
 Aggregate
   ->  Index Only Scan using consignments_state on consignments
         Index Cond: (state = $1)
(3 rows)

DISCARD PLANS
           QUERY PLAN           
--------------------------------
 Aggregate
   ->  Seq Scan on consignments
         Filter: (state = $1)
(3 rows)

The advice was set and nothing changed until DISCARD PLANS. The same applies to plans cached inside PL/pgSQL. A prepared statement with no parameters always uses a generic plan, so for those the cache is the only plan there is. Behind a pooler it is worse in three ways. Advice set with SET in one session never reaches the other server connections. Under transaction pooling, the same SET stays on the server connection after your transaction ends and steers whichever client’s queries land there next, so use SET LOCAL inside the transaction, or set the advice per role or per database. And a connection holding a cached generic plan may not plan the statement again until something invalidates that plan or DISCARD PLANS runs on that connection. Notice also that none of these outputs carries a feedback section: for prepared statements the module skips generating feedback unless pg_plan_advice.always_store_advice_details is on, which the docs suggest enabling only in the session that needs it.

Stashing advice by query identifier

pg_stash_advice applies advice without changing application code: load the module, normally through shared_preload_libraries, and set pg_stash_advice.stash_name per role, per database or in postgresql.conf. A stash maps query identifiers to advice strings and lives in shared memory; you look the identifier up, store the advice, and point pg_stash_advice.stash_name at the stash. Here the pin is chosen for the common case, a count of delivered consignments, where scanning the whole table is the right call.

CREATE EXTENSION pg_stash_advice;
CREATE EXTENSION pg_stat_statements;
SELECT pg_create_advice_stash('night_shift');
SELECT count(*) FROM consignments WHERE state = 'delivered';
SELECT pg_set_stashed_advice('night_shift', queryid, 'SEQ_SCAN(consignments) NO_GATHER(consignments)')
FROM pg_stat_statements
WHERE query = 'SELECT count(*) FROM consignments WHERE state = $1'
  AND dbid = (SELECT oid FROM pg_database WHERE datname = current_database());
SELECT stash_name, advice_string FROM pg_get_advice_stash_contents('night_shift');
CREATE EXTENSION
CREATE EXTENSION
 pg_create_advice_stash 
------------------------
 
(1 row)

 count  
--------
 294000
(1 row)

 pg_set_stashed_advice 
-----------------------
 
(1 row)

 stash_name  |                 advice_string                  
-------------+------------------------------------------------
 night_shift | SEQ_SCAN(consignments) NO_GATHER(consignments)
(1 row)

Now the same query shape with both values, in a session that names the stash.

LOAD 'pg_stash_advice';
SET pg_stash_advice.stash_name = 'night_shift';
EXPLAIN (COSTS OFF) SELECT count(*) FROM consignments WHERE state = 'delivered';
EXPLAIN (COSTS OFF) SELECT count(*) FROM consignments WHERE state = 'held';
LOAD
SET
                 QUERY PLAN                  
---------------------------------------------
 Aggregate
   ->  Seq Scan on consignments
         Filter: (state = 'delivered'::text)
 Supplied Plan Advice:
   SEQ_SCAN(consignments) /* matched */
   NO_GATHER(consignments) /* matched */
(6 rows)

               QUERY PLAN                
-----------------------------------------
 Aggregate
   ->  Seq Scan on consignments
         Filter: (state = 'held'::text)
 Supplied Plan Advice:
   SEQ_SCAN(consignments) /* matched */
   NO_GATHER(consignments) /* matched */
(6 rows)

The rare value got the common value’s plan. That is the query identifier working as designed: it ignores the values of constants, which is what makes pg_stat_statements useful, and it means a stashed pin is a pin for every value at once. Before stashing anything, check whether the query’s parameters are skewed. If they are, the pin is a choice about which values get the bad plan.

One identifier, two schemas

Since PostgreSQL 18, query identifiers group together queries that use the same relation name, and the 18 release notes add that this holds even when the tables in different schemas have different column names. So a table of the same name in a second schema produces the same identifier, and a stash follows it there. The demonstration below runs on 19. A schema-per-tenant layout is where this lands.

CREATE SCHEMA branch_b;
CREATE TABLE branch_b.consignments (LIKE public.consignments INCLUDING INDEXES);
INSERT INTO branch_b.consignments SELECT * FROM public.consignments WHERE consignment_id <= 5000;
ANALYZE branch_b.consignments;
LOAD 'pg_stash_advice';
SET pg_stash_advice.stash_name = 'night_shift';
SET search_path = branch_b, public;
EXPLAIN (COSTS OFF) SELECT count(*) FROM consignments WHERE state = 'held';
SELECT count(*) FROM consignments WHERE state = 'held';
SELECT calls FROM pg_stat_statements
WHERE query = 'SELECT count(*) FROM consignments WHERE state = $1'
  AND dbid = (SELECT oid FROM pg_database WHERE datname = current_database());
CREATE SCHEMA
CREATE TABLE
INSERT 0 5000
ANALYZE
LOAD
SET
SET
               QUERY PLAN                
-----------------------------------------
 Aggregate
   ->  Seq Scan on consignments
         Filter: (state = 'held'::text)
 Supplied Plan Advice:
   SEQ_SCAN(consignments) /* matched */
   NO_GATHER(consignments) /* matched */
(6 rows)

 count 
-------
   100
(1 row)

 calls 
-------
     2
(1 row)

The count of one hundred is the second schema’s table, and the advice stored against the first schema’s query was applied to it. pg_stat_statements agrees: one row, two calls, one from each schema. A pin added for the tenant whose plan flipped is a pin for every tenant whose table has that name, sized very differently or not.

How a stashed pin goes stale

Nothing ties stashed advice to the objects it names. Store a pin that names an index, rename the index as a migration might, and the pin still matches the query, no longer applies, and says so only to someone running EXPLAIN.

SELECT pg_set_stashed_advice('night_shift', queryid, 'INDEX_SCAN(consignments public.consignments_state)')
FROM pg_stat_statements
WHERE query = 'SELECT count(*) FROM consignments WHERE state = $1'
  AND dbid = (SELECT oid FROM pg_database WHERE datname = current_database());
LOAD 'pg_stash_advice';
SET pg_stash_advice.stash_name = 'night_shift';
EXPLAIN (COSTS OFF) SELECT count(*) FROM consignments WHERE state = 'held';
ALTER INDEX consignments_state RENAME TO consignments_state_v2;
EXPLAIN (COSTS OFF) SELECT count(*) FROM consignments WHERE state = 'held';
 pg_set_stashed_advice 
-----------------------
 
(1 row)

LOAD
SET
                             QUERY PLAN                             
--------------------------------------------------------------------
 Aggregate
   ->  Index Scan using consignments_state on consignments
         Index Cond: (state = 'held'::text)
 Supplied Plan Advice:
   INDEX_SCAN(consignments public.consignments_state) /* matched */
(5 rows)

ALTER INDEX
                                        QUERY PLAN                                        
------------------------------------------------------------------------------------------
 Aggregate
   ->  Index Only Scan using consignments_state_v2 on consignments
         Index Cond: (state = 'held'::text)
 Supplied Plan Advice:
   INDEX_SCAN(consignments public.consignments_state) /* matched, inapplicable, failed */
(5 rows)

Before the rename the pin matched and held: an index scan on the named index, as asked. After it, the same advice is reported as failed and the planner chooses for itself. Here it picked an index-only scan on the renamed index, so the plan has already left the pinned shape, harmlessly this time, and nothing outside EXPLAIN said so. The day the estimates shift, the pin you believe is holding the plan in place is holding nothing. The data drifting under a valid pin is the other way this goes, and the docs’ opening warning is about that case. Either way, the stash contents want a scheduled review against EXPLAIN with the stash active, and pg_get_advice_stash_contents is the list to review. One risk we have not tested: stashes live in server-wide shared memory with no database in their key, so check whether a stash named in one database’s settings can reach same-shaped queries in another before relying on it.

What running it costs

Applying advice has a cost the docs call noticeable even when the plan does not change, which is the argument for stashing advice only for queries that need it. Stashes live in dynamically allocated shared memory, so their size counts against the server. pg_stash_advice.persist is on by default, so stashes are written to pg_stash_advice.tsv in the data directory, checked for changes every thirty seconds, but only by a background worker, and that worker starts on its own only when the module is in shared_preload_libraries. Without it nothing reaches disk, and because the stashes live in shared memory, a restart loses them. pg_start_stash_advice_worker() starts the worker by hand; it loads nothing from disk, but it saves what is there, so the next restart with the module preloaded brings the stashes back. The identifier has to be computed, so compute_query_id must be on; at its default of auto, loading pg_stash_advice turns it on.

The security model is the part to read twice. Only a superuser, or a role granted execute on the functions, can change a stash. Any user can set pg_stash_advice.stash_name in their own session, and the docs warn that this can reveal the stash’s contents, so an advice string should never carry anything you would not show every role on the server.

Put every Postgres you run on autopilot.

We onboard teams in small batches. Tell us about your fleet and we will reach out when a seat opens. One email, no drip campaign.