
© Laurenz Albe 2026
One of the more important new v19 features is the option to force the planner's hand with the help of pg_plan_advice and pg_stash_advice. You may have heard that “PostgreSQL v19 finally has query hints”, which is not entirely wrong. But if you are used to Oracle style query hints, you may be surprised and confused, because the PostgreSQL feature works in a different way. So I'd like to explain the feature with the aid of a fairly realistic example.
What, query hints? I thought that PostgreSQL rejects the concept!
I is true that PostgreSQL had refused to add query hints for a long time. As I am writing this, the PostgreSQL Wiki still has the following under Features We Do Not Want:
"Oracle-style" optimizer hints
Optimizer hints, as implemented in Oracle and other RDBMSes, are used to work around problems in the optimizer and introduce upgrade and maintenance issues. We would rather have such problems reported and fixed. We have discussed a more sophisticated system of per-class cost adjustment instead, but a specification remains to be developed. See Optimizer Hints Discussion for further information.
But then, there have been “hints” even before pg_stash_advice
However, PostgreSQL is not controlled by a single person or entity, and that decision has never been unanimous. Also, reality being the way it is, there have always been cases where the best statistics and the smartest query planner together made the wrong decision. Consequently, people have felt the need to force the planner's hand. Out of that need, a couple of “hint-like” approaches to the problem have developed:
- The PostgreSQL extension pg_hint_plan, which provides Oracle-style optimizer hints without the need to modify the server code. It is a great example of PostgreSQL's famous extensibility: if you can't get the feature you want into core PostgreSQL, scratch your own itch in an extension.
- PostgreSQL has a number of parameters named
enable_*. These allow you to disable certain types of plan nodes. You rarely ever disable a node type globally. But if I could not find a better solution, disabling (for example) nested loop joins for a single query withSET LOCAL enable_nestloop = offhas sometimes saved the day, leaving a bad taste in my mouth. These parameters are a coarse instrument; in a complicated query, disabling a node type across the board may help in one place, but cause damage somewhere else. - There are a number of semi-documented tricks to force the planner, like
OFFSET 0,WITH ... MATERIALIZEDorORDER BY id + 0, which provide optimizer barriers or prevent the use of certain indexes. Arguably, they are query hints in disguise, and the fact that they have been carefully preserved prove the need to nudge the planner occasionally.
So, adding pg_plan_advice and pg_stash_advice is giving in to the need, in a way. To keep face, the feature is advertised as providing plan stability. Plan stability is the good reason for using query hints: you'd rather have a query plan remain stable and degrade gradually than falling off a cliff when the optimizer decides to suddenly switch to a different plan. Also, PostgreSQL didn't repeat what I consider the worst part of Oracle's design: having hints as comments in the statement force you to modify the statement itself, which won't work at all with query generators. As a mitigating circumstance, I concede that Oracle's design probably stems from a time when people usually wrote SQL by hand.
An example as showcase for pg_plan_advice and pg_stash_advice
My example is a database with three tables that model customers ordering goods from a vendor. I used unlogged tables throughout, since all I want to demonstrate is query performance. I configured PostgreSQL v19 with the default values, except shared_buffers, which I set big enough to hold all the data. That way, it is easy to compare the performance of my queries.
A table of producers
First, there are a hundred producers of the goods to sell:
CREATE UNLOGGED TABLE producers ( producer_id bigint PRIMARY KEY, producer_name text UNIQUE NOT NULL ); INSERT INTO producers (producer_id, producer_name) VALUES (1, 'ACME'); INSERT INTO producers (producer_id, producer_name) SELECT i, 'producer_' || i FROM generate_series(2, 100) AS i; VACUUM (ANALYZE) producers;
A table of goods
Then, there are around two thousand different types of goods to sell:
CREATE UNLOGGED TABLE goods ( good_id bigint PRIMARY KEY, producer_id bigint REFERENCES producers NOT NULL, good_name text NOT NULL ); INSERT INTO goods (good_id, producer_id, good_name) SELECT i, CASE i % 2 WHEN 0 THEN (i / 2 - 1) % 99 + 2 ELSE 1 END, 'good_' || i FROM generate_series(1, 1980) AS i; VACUUM (BUFFER_USAGE_LIMIT 0, ANALYZE) goods; CREATE INDEX goods_producer_idx ON goods (producer_id);
I deliberately added some skew to the data: producer ACME produces half the goods, while the remaining producers each only produce ten each. This uneven distribution will cause problems later on.
A table of orders
Finally, we have a table of five million orders by over ten thousand customers. To keep the example simple, I omit a table of customers; I will use customer_id to reference customers in my query.
CREATE UNLOGGED TABLE orders ( order_id bigint PRIMARY KEY, good_id bigint REFERENCES goods NOT NULL, /* should reference "customers" */ customer_id bigint NOT NULL, order_items integer NOT NULL, order_date date NOT NULL ); INSERT INTO orders (order_id, good_id, customer_id, order_items, order_date) SELECT i, (i - 1) % 1980 + 1, (i - 1) % 12373 + 1, 10, '2026-11-03' FROM generate_series(1, 5000000) AS i; VACUUM (BUFFER_USAGE_LIMIT 0, ANALYZE) orders; CREATE INDEX orders_good_idx ON orders (good_id); CREATE INDEX orders_customer_idx ON orders (customer_id);
The orders are evenly distributed across the goods and the customers*.
The problem query
Our problem query figures out how many orders and how many ordered items a single customer ordered from a single producer.
SELECT count(*) AS order_count, sum(o.order_items) AS total_items FROM producers AS p JOIN goods AS g USING (producer_id) JOIN orders AS o USING (good_id) WHERE p.producer_name = 'ACME' AND o.customer_id = 42;
Before running the query, I make sure that all data are cached in shared buffers. The query turns out to be fast for all cases except for producer ACME, where is takes almost half a second. Here is the execution plan:
QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------- Aggregate (cost=790.76..790.77 rows=1 width=16) (actual time=405.572..405.575 rows=1.00 loops=1) Buffers: shared hit=9240 -> Nested Loop (cost=38.80..790.74 rows=4 width=4) (actual time=4.824..405.446 rows=202.00 loops=1) Buffers: shared hit=9240 -> Nested Loop (cost=4.43..22.93 rows=20 width=8) (actual time=0.113..0.725 rows=990.00 loops=1) Buffers: shared hit=18 -> Seq Scan on producers p (cost=0.00..2.25 rows=1 width=8) (actual time=0.021..0.028 rows=1.00 loops=1) Filter: (producer_name = 'acme'::text) Rows Removed by Filter: 99 Buffers: shared hit=1 -> Bitmap Heap Scan on goods g (cost=4.43..20.48 rows=20 width=16) (actual time=0.088..0.393 rows=990.00 loops=1) Recheck Cond: (p.producer_id = producer_id) Heap Blocks: exact=15 Buffers: shared hit=17 -> Bitmap Index Scan on goods_producer_idx (cost=0.00..4.43 rows=20 width=0) (actual time=0.064..0.064 rows=990.00 loops=1) Index Cond: (producer_id = p.producer_id) Index Searches: 1 Buffers: shared hit=2 -> Bitmap Heap Scan on orders o (cost=34.37..38.38 rows=1 width=12) (actual time=0.407..0.407 rows=0.20 loops=990) Recheck Cond: ((customer_id = 42) AND (g.good_id = good_id)) Heap Blocks: exact=202 Buffers: shared hit=9222 -> BitmapAnd (cost=34.37..34.37 rows=1 width=0) (actual time=0.404..0.404 rows=0.00 loops=990) Buffers: shared hit=9020 -> Bitmap Index Scan on orders_customer_idx (cost=0.00..7.46 rows=404 width=0) (actual time=0.028..0.028 rows=405.00 loops=990) Index Cond: (customer_id = 42) Index Searches: 990 Buffers: shared hit=3960 -> Bitmap Index Scan on orders_good_idx (cost=0.00..26.55 rows=2525 width=0) (actual time=0.333..0.333 rows=2525.25 loops=990) Index Cond: (good_id = g.good_id) Index Searches: 990 Buffers: shared hit=5060 Planning: Buffers: shared hit=18 Planning Time: 0.764 ms Execution Time: 405.646 ms
Understanding the problem
Before we can use pg_stash_advice to force a good execution plan, we have to understand why the query performs badly. The place where the planner goes wrong is when it estimates the result set count of the bitmap index scan on goods: the actual 990 rows are almost fifty times as many as the estimated 20 rows. The problem manifests in the subsequent join with orders. With only twenty goods, PostgreSQL chooses a nested loop join, expecting to scan orders only twenty times. The 990 actual iterations of the loop are where the executor spends the bulk of its time.
The problem is not that PostgreSQL doesn't know about the uneven distribution of the producers in goods. As I described in my article comparing enum types and lookup tables, the problem is that at query planning time, PostgreSQL does not know which producer_id corresponds to the producer_name “ACME”. While PostgreSQL is well aware that the half of the goods have producer_id 1, it only learns that ACME has that producer_id when it scans the producer table at query execution time.
I think that there is room for improvement here: PostgreSQL could scan the lookup table during query planning and infer the likely producer_id. Yes, that would be a violation of the boundary between query planner and query executor. However, there is a precedent: to estimate the prevalence of values outside the histogram boundaries, the query planner probes indexes to find the actual minimum or maximum. On the other hand, that has proved problematic in the past, and there were a number of bugfixes to keep the planner from spending excessive time scanning indexes, so I am not certain that we should go down that rabbit hole again.
Anyway, since the query planner doesn't know which producer_id corresponds to ACME, it uses an average to estimate the number of rows found in goods. That estimate is fairly correct for all of the producers other than ACME, but is wildly inaccurate for that outlier. This leads to the bad execution plan.
A better execution plan for use with pg_stash_advice
The key to a better query plan is the observation that orders are evenly distributed across the customers. So it makes sense to start the query execution by scanning orders for the rows belonging to a certain customer, which will return a moderate number of results. Then we can join goods and producers, which won't increase the number of rows. While this may not be the perfect execution plan for producers other than ACME, it should reliably prevent excessive query execution times.
Using pg_plan_advice to find the correct query hint
While pg_stash_advice is the extension we will use to force a certain query hint, pg_plan_advice is the extension we use for finding the correct hint. We have to add pg_plan_advice to shared_preload_libraries to be able to use it. Since this requires a restart, we use the opportunity to also add pg_stash_advice to shared_preload_libraries to save us another restart later on.
With pg_plan_advice activated, we can use EXPLAIN (ANALYZE, PLAN_ADVICE) to show the hints that correspond to the bad query execution. They look as follows:
Generated Plan Advice: JOIN_ORDER(p g o) NESTED_LOOP_PLAIN(g o) SEQ_SCAN(p) BITMAP_HEAP_SCAN(g o) NO_GATHER(p g o)
The first hint tells us how to force the join order. To test if our idea for a better execution plan actually works, we set the parameter pg_plan_advice.advice to our proposed join order:
SET pg_plan_advice.advice = 'JOIN_ORDER(o g p)';
Then we run EXPLAIN (ANALYZE, PLAN_ADVICE) again and get:
Aggregate (cost=1563.45..1563.46 rows=1 width=16) (actual time=9.824..9.826 rows=1.00 loops=1) Buffers: shared hit=224 read=201 -> Nested Loop (cost=67.11..1563.43 rows=4 width=4) (actual time=0.922..9.765 rows=202.00 loops=1) Join Filter: (p.producer_id = g.producer_id) Rows Removed by Join Filter: 203 Buffers: shared hit=224 read=201 -> Hash Join (cost=67.11..1555.12 rows=404 width=12) (actual time=0.899..9.545 rows=405.00 loops=1) Hash Cond: (o.good_id = g.good_id) Buffers: shared hit=223 read=201 -> Bitmap Heap Scan on orders o (cost=7.56..1494.51 rows=404 width=12) (actual time=0.354..8.705 rows=405.00 loops=1) Recheck Cond: (customer_id = 42) Heap Blocks: exact=405 Buffers: shared hit=208 read=201 -> Bitmap Index Scan on orders_customer_idx (cost=0.00..7.46 rows=404 width=0) (actual time=0.028..0.028 rows=405.00 loops=1) Index Cond: (customer_id = 42) Index Searches: 1 Buffers: shared hit=4 -> Hash (cost=34.80..34.80 rows=1980 width=16) (actual time=0.535..0.536 rows=1980.00 loops=1) Buckets: 2048 Batches: 1 Memory Usage: 109kB Buffers: shared hit=15 -> Seq Scan on goods g (cost=0.00..34.80 rows=1980 width=16) (actual time=0.006..0.117 rows=1980.00 loops=1) Buffers: shared hit=15 -> Materialize (cost=0.00..2.25 rows=1 width=8) (actual time=0.000..0.000 rows=1.00 loops=405) Storage: Memory Maximum Storage: 17kB Buffers: shared hit=1 -> Seq Scan on producers p (cost=0.00..2.25 rows=1 width=8) (actual time=0.005..0.010 rows=1.00 loops=1) Filter: (producer_name = 'acme'::text) Rows Removed by Filter: 99 Buffers: shared hit=1 Planning: Buffers: shared hit=18 Planning Time: 0.265 ms Supplied Plan Advice: JOIN_ORDER(o g p) /* matched */ Generated Plan Advice: JOIN_ORDER(o g p) NESTED_LOOP_MATERIALIZE(p) HASH_JOIN(g) SEQ_SCAN(g p) BITMAP_HEAP_SCAN(o) NO_GATHER(p g o)
We see that our hint was used (JOIN_ORDER(o g p) /* matched */), and the execution time is way better.
Forcing a query hint with pg_stash_advice
After we have made sure that this plan also works reasonably well for other producers, we want to make sure that it will be used from now on. pg_plan_advice is not the right tool for that — it is for experimenting and testing, like we did above. We can hardly stuff all the hints for all our queries into pg_plan_advice.advice. Also, our hint might accidentally apply to some other query too and give us a bad plan there.
We need pg_stash_advice to make the hint persistent. We have to add that extension to shared_preload_libraries and restart PostgreSQL, which we already did for when we enabled pg_plan_advice. pg_stash_advice allows us to create a stash of hints, where each hint is assigned to the correct query by the query ID, which is a hash of the parsed query. We can get the query ID with EXPLAIN (VERBOSE) once pg_stash_advice is active (or if the parameter compute_query_id is set to on). The query ID for our query is 7090840992297492552, so we can proceed as follows:
/* create the stash */ SELECT pg_create_advice_stash('myapp'); /* add the hint to the stash */ SELECT pg_set_stashed_advice('myapp', 7090840992297492552, 'JOIN_ORDER(o g p)');You need to be a superuser to call these functions. Next, we can make that stash active for all connections to our database:
ALTER DATABASE mydb SET pg_stash_advice.stash_name = 'myapp';
Note that this setting will only become active for new connections to the database, so we need to disconnect and reconnect to verify that PostgreSQL uses our hint as it should.
Persistence of hints from pg_stash_advice
The stashes of hints live in shared memory, which gets lost at server shutdown. However, PostgreSQL by default will regularly persist the stashes to the file pg_stash_advice.tsv in the data directory and load them after a restart. That means that you don't lose your query hints during a database restart or a crash.
However, the query hints won't be included in the output of pg_dump, which means that they won't survive the export and import of a database. Since pg_upgrade also uses pg_dump to export the database metadata, it will also ignore the hints. That means that a major upgrade in PostgreSQL will not upgrade your stashes of hints. I couldn't find any discussion on the hackers mailing list that indicates that that was a deliberate decision, but I think that it is fortunate. Everybody recommends that you reassess your query hints when you upgrade, but too few people actually do it. With pg_stash_advice, you are at least forced to deliberately transfer your hints after an upgrade, so you are more likely to at least have another glance at them.
Is pg_stash_advice the best way to tune this query?
Probably not. For example, if I set random_page_cost to 1.1, PostgreSQL will pick a good plan for our problem query. The advantage of tuning the query with indexes or parameter changes is that the query planner is still free: if our data change over time, it could pick a plan that works better than the one I found.
Still, once you have been burnt by a query plan that flipped and became slow enough to cause an outage, you might prefer a stable plan over the best plan. With a stable plan, you might experience a gradual decline in the performance of the query, but you won't get a sudden and devastating plan change. That gives you time to find a remedy for the decline, which is much better than having to fix a bad query plan under pressure on Monday morning.
There are other ways to force the join order, but they are arguably worse than using pg_stash_advice. Yet I advise to use a light hand when using pg_stash_advice: observe that I didn't force the join method or how tables should be scanned. That gives the optimizer some freedom to adapt to changes while you keep it from getting lost in the woods.
There is yet another way to make our query behave: we can split it into two queries. The problem with the original query was that PostgreSQL doesn't know at query planning time which producer_id belongs to producer ACME. So we can first query producers for ACME's producer_id and then query only goods and orders:
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) AS order_count, sum(o.order_items) AS total_items FROM goods AS g JOIN orders AS o USING (good_id) WHERE g.producer_id = 1 AND o.customer_id = 42; QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------- Aggregate (cost=1548.70..1548.71 rows=1 width=16) (actual time=1.421..1.424 rows=1.00 loops=1) Buffers: shared hit=424 -> Hash Join (cost=59.69..1547.69 rows=202 width=4) (actual time=0.757..1.395 rows=202.00 loops=1) Hash Cond: (o.good_id = g.good_id) Buffers: shared hit=424 -> Bitmap Heap Scan on orders o (cost=7.56..1494.51 rows=404 width=12) (actual time=0.199..0.727 rows=405.00 loops=1) Recheck Cond: (customer_id = 42) Heap Blocks: exact=405 Buffers: shared hit=409 -> Bitmap Index Scan on orders_customer_idx (cost=0.00..7.46 rows=404 width=0) (actual time=0.088..0.089 rows=405.00 loops=1) Index Cond: (customer_id = 42) Index Searches: 1 Buffers: shared hit=4 -> Hash (cost=39.75..39.75 rows=990 width=8) (actual time=0.545..0.546 rows=990.00 loops=1) Buckets: 1024 Batches: 1 Memory Usage: 47kB Buffers: shared hit=15 -> Seq Scan on goods g (cost=0.00..39.75 rows=990 width=8) (actual time=0.010..0.297 rows=990.00 loops=1) Filter: (producer_id = 1) Rows Removed by Filter: 990 Buffers: shared hit=15 Planning: Buffers: shared hit=14 Planning Time: 0.505 ms Execution Time: 1.483 ms
Splitting up the query works well, but it means changing the application code, which is annoying. Also, if the network latency between application and database is high, an extra round trip is painful, even for a short query.
Conclusion
If you need to prevent the query planner from choosing a bad query plan, you can use pg_plan_advice to come up with good query hints and pg_stash_advice to enforce them. Try the classical methods first, such as creating indexes, adapting optimizer parameters, rewriting the query or tuning the optimizer statistics to get correct estimates. If you feel the need to force the optimizer's hand to get plan stability, use a gentle hand.
Don't forget that a major upgrade will lose your query hints. Take the opportunity to reassess your hints during an upgrade!
The post Plan stability with pg_stash_advice: how to do it in practice appeared first on CYBERTEC PostgreSQL | Services & Support.