The v19 release introduces pg_plan_advice and pg_stash_advice, which let you override the planner's choices. Calling this "query hints" for PostgreSQL is not entirely wrong, but the mechanism differs sharply from the Oracle model: hints are not comments embedded in the statement, they are stored out-of-band and matched to a query by its ID. That matters for generated SQL, where editing the statement text is not an option.
Why the project changed course
PostgreSQL long declined to adopt hints, and the Wiki's "Features We Do Not Want" page still says so:
"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.
That stance was never unanimous, and in practice users had several ways to nudge the planner already. The pg_hint_plan extension supplies Oracle-style hints without patching the server — extensibility standing in for core features. The enable_* parameters allow disabling node types, typically per query via SET LOCAL enable_nestloop = off; this is a blunt tool, since a single query with several join sites may well be helped at one and harmed at another. And semi-documented tricks such as OFFSET 0, WITH ... MATERIALIZED or ORDER BY id + 0 act as optimizer barriers or block index use. Those survive as deliberately supported behavior, which shows the need was real.
The core justification offered for the new feature is plan stability: keeping a plan from swinging to something far worse when the optimizer changes its mind. (Unlike Oracle, PostgreSQL does not require hints to live as comments inside the statement, which would break query generators.)
Test schema
The example models customers ordering goods from producers. All tables are unlogged; PostgreSQL is v19 at default settings except shared_buffers, sized to hold the whole data set. One hundred producers:
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;
Around two thousand goods:
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);
Note the deliberate skew: ACME produces half the goods, every other producer makes ten. This distribution is the source of the trouble.
Five million orders from over ten thousand customers; no customer table, only customer_id:
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);
Orders are spread evenly across goods and customers.*
The slow query
The query counts orders and ordered items for one customer buying from one 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;
All data was cached in shared buffers before measurement. Every producer runs fast except ACME, which takes almost half a second:
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
Root cause
The estimator misses the row count of the bitmap index scan on goods: 990 actual rows against 20 estimated, a factor of almost fifty. That error propagates into the join with orders: expecting twenty goods, the planner picks a nested loop, planning on twenty scans of orders while the executor performs 990.
The planner is not ignorant of the skew in goods — it knows half the rows carry producer_id 1. What it cannot know at planning time is that the name "ACME" resolves to producer_id 1. The mapping is learned only when the producer table is scanned at execution time. So the estimate for goods falls back on an average, which is right for every producer except the outlier.
There is room for improvement: the planner could read the lookup table and infer the likely producer_id, crossing the planner/executor boundary. There is precedent — the planner probes indexes to find real min/max values for estimates outside the histogram — but past experience with that mechanic required bugfixes against excessive index probing, so it is not obviously a safer direction.
The fix for a stable plan follows from the even spread of orders among customers: begin by scanning orders for the one customer, returning a modest row count, then join goods and producers without multiplying rows. That is not necessarily the textbook-best plan for other producers, but it reliably avoids the cliff.
Finding the right hint with pg_plan_advice
pg_plan_advice is the exploration tool; add it to shared_preload_libraries (one restart) — and add pg_stash_advice at the same time so a second restart isn't needed later. With it loaded, EXPLAIN (ANALYZE, PLAN_ADVICE) reports the hints matching the actual plan:
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 gives the join order. To test the alternative, put the proposed order into pg_plan_advice.advice:
SET pg_plan_advice.advice = 'JOIN_ORDER(o g p)';
Re-running EXPLAIN (ANALYZE, PLAN_ADVICE):
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)
The hint is marked used (JOIN_ORDER(o g p) /* matched */) and the runtime improves substantially.
Persisting hints with pg_stash_advice
pg_plan_advice is for experiments — hints for all queries cannot live in a single session parameter, and a generic hint risks matching an unrelated query and wrecking its plan. pg_stash_advice makes the hint permanent: hints sit in a stash keyed by query ID, a hash of the parsed query, visible in EXPLAIN (VERBOSE) once the extension is active (or with compute_query_id = on). This query's ID is 7090840992297492552:
/* 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)');
These functions require a superuser. The stash is then enabled for all connections to the database:
ALTER DATABASE mydb SET pg_stash_advice.stash_name = 'myapp';
The setting applies only to new connections — disconnect and reconnect to confirm the hint is being applied.
Durability across restarts and upgrades
Stashes live in shared memory, which vanishes at shutdown, but PostgreSQL regularly writes them to the file pg_stash_advice.tsv in the data directory and reloads it on startup, so hints survive restarts and crashes. They are not included in pg_dump output, and pg_upgrade exports database metadata via pg_dump, so a major-version upgrade does not carry the stashes over. No hackers mailing list discussion suggests this was intentional, but it is arguably a benefit: everyone says hints should be reassessed at upgrade time and few do; here the transfer has to be done deliberately, which at least encourages a second look.
Alternatives and their trade-offs
Forcing a plan with pg_stash_advice is usually not the best fix for a misbehaving query. In the case above, lowering random_page_cost to 1.1 makes PostgreSQL choose a good plan on its own. Index and parameter tuning leave the planner free to react when the data change, so it may eventually find something better than the plan you pinned.
The counterargument is outage experience. A query plan that flips to something slow can take a system down; a stable plan that degrades gradually gives you room to find a remedy. That trade — a slow decline instead of a sudden collapse — is often what you want if you have already been through an incident.
Other mechanisms exist for forcing a join order, and they are arguably worse than pg_stash_advice. Even so, use a light hand. In the example, the join method and the way tables are scanned were left unforced, so the optimizer still has some freedom to adapt while being kept away from the worst choices.
Splitting the query
Another option is to break the query in two. The original problem was that PostgreSQL cannot know at planning time which producer_id belongs to producer ACME. So query producers first for ACME's producer_id, 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
The split works, but it requires changing application code, which is annoying. With high network latency between application and database, the extra round trip hurts even for a short query.
Recommendations
To stop the planner from picking a bad plan, pg_plan_advice can produce good hints and pg_stash_advice can enforce them. Exhaust the classical remedies first: create indexes, adjust optimizer parameters, rewrite the query, and tune optimizer statistics so estimates are correct. Intervene on the optimizer only when you need plan stability, and then gently.
Remember that a major upgrade discards your query hints. Use the upgrade as an occasion to reassess them.



