PG 19 Plan Advice: “Matched” Does Not Mean the Plan Stayed the Same
Hands-on tests of pg_plan_advice and pg_stash_advice explain matched feedback, plan drift and persistent constraints, with an availability check on IvorySQL 5.6.
Shang Lei
Testing pg_plan_advice on PG 19.0, with an availability check on IvorySQL 5.6
Introduction
PostgreSQL 19 introduces an easily overlooked module:
pg_plan_advice. It lets DBAs constrain key optimizer decisions per statement, persist those constraints, and inspect feedback, without modifying SQL or installing a third-party extension. Oracle DBAs have had a related mechanism since 11g: SQL Plan Baseline.This article tests the mechanism on PG 19.0 and focuses on three questions: how it differs from hints, what it actually means when advice is marked
matched, and when IvorySQL users can use it.
1. Plan drift is a persistent problem, with different remedies
A SQL statement runs well for six months, then suddenly becomes ten times slower. The SQL text and indexes have not changed. Only the statistics, data distribution, or a configuration setting changed. The execution plan is different, and nobody knows when it changed.
The difficult part is the lack of visibility. Slow-query logs tell you a query was slow, but not which plan it used last time. By the time the DBA notices, users are already complaining.
Oracle's answer is SQL Plan Baseline, available since 11g. The idea is direct: store the plans considered good for a statement as objects, then let the optimizer choose among them. A newly generated plan must be accepted through evolution before it can replace them; otherwise it remains a candidate. The database manages storage, acceptance policies, and the evolution process.
PostgreSQL has long lacked a direct counterpart. To influence a plan, users have relied on extensions such as pg_hint_plan: add /*+ IndexScan(t idx) */ to an SQL comment and let the extension alter the optimizer's decisions.
The capabilities of pg_hint_plan deserve a fair description. It already provides two ways around some of those limitations:
- Hint Table: Store hints with their
query_idinhint_plan.hintsand match them by query ID withcompute_query_idenabled. Hints then need not appear in the SQL text, and changing them does not require changing and redeploying SQL. Table hints take precedence over comment hints. Enablepg_hint_plan.enable_hint_table, which defaults tooff. - Debugging feedback:
pg_hint_plan.debug_print(off/on/detailed/verbose), together withmessage_level, can log parsing and application details.parse_messagescontrols the output level for parsing errors. Saying that hint application is completely invisible would be inaccurate. The feedback must, however, be enabled explicitly and is written to logs, unlike plan advice's per-item annotations directly inEXPLAIN.
The remaining differences matter:
- A statement can carry only one hint set in its comments. Although Hint Table can distinguish
query_idplusapplication_name, it still assigns a fixed hint to a query ID rather than storing multiple plans and evolving among them like SQL Plan Baseline. - Hint syntax and available hint names follow the extension version and need revalidation after major upgrades.
- Feedback requires configuration: enable Hint Table or
debug_printand inspect logs. The default workflow offers little visibility.
PG 19 offers something different. It calls the mechanism plan advice, rather than hints.
2. Constraints live outside SQL comments and can be read back
First, installation has a detail that can trip you up.
pg_plan_advice is a module, not an extension. It does not appear in pg_available_extensions, and CREATE EXTENSION pg_plan_advice fails. Its library directory contains a .so file:
$ docker exec pg19 ls /usr/lib/postgresql/19/lib | grep -i advice
pg_plan_advice.so
pg_stash_advice.so
Load it either with LOAD 'pg_plan_advice' for the current session or through shared_preload_libraries globally. By contrast, pg_stash_advice is an extension and requires CREATE EXTENSION. These are different components; section 5 returns to this distinction.
Loading the module adds the PLAN_ADVICE option to EXPLAIN. It does not change the plan. It simply expresses the optimizer's decisions as advice:
pg19=# EXPLAIN (COSTS OFF, PLAN_ADVICE)
SELECT * FROM join_fact f JOIN join_dim d ON f.dim_id = d.id
WHERE f.v < 300;
QUERY PLAN
--------------------------------------------------
Hash Join
Hash Cond: (f.dim_id = d.id)
-> Gather
Workers Planned: 1
-> Parallel Seq Scan on join_fact f
Filter: (v < 300)
-> Hash
-> Seq Scan on join_dim d
Generated Plan Advice:
JOIN_ORDER(f d)
HASH_JOIN(d)
SEQ_SCAN(f d)
GATHER(f)
NO_GATHER(d)

Figure 1. Output of
EXPLAIN (COSTS OFF, PLAN_ADVICE)from the actual PG 19.0 terminal session (MobaXterm → 192.168.3.110). The optimizer records five decisions, including which table uses parallelism.
Understanding these five lines explains the design:
| Advice | Meaning |
|---|---|
JOIN_ORDER(f d) | f is the driving table, with d joined first |
HASH_JOIN(d) | d is on the inner side of a hash join |
SEQ_SCAN(f d) | Both tables use sequential scans |
GATHER(f) | Place a Gather above f, enabling a parallel scan |
NO_GATHER(d) | Do not place a Gather above d |
Notice the last two lines. The official documentation's example does not use parallelism and shows only JOIN_ORDER, HASH_JOIN, SEQ_SCAN, and NO_GATHER. This query uses parallelism, adding GATHER. The advice string records the optimizer's actual decisions, including which table uses parallelism and which does not.
It is a complete snapshot, rather than a summary.
The example uses five tags. The full list contains 20, grouped here to show the mechanism's scope:
| Category | Tags |
|---|---|
| Scan methods | SEQ_SCAN, TID_SCAN, INDEX_SCAN, INDEX_ONLY_SCAN, FOREIGN_JOIN, BITMAP_HEAP_SCAN, DO_NOT_SCAN |
| Join order | JOIN_ORDER |
| Join methods | HASH_JOIN, MERGE_JOIN_PLAIN, MERGE_JOIN_MATERIALIZE, NESTED_LOOP_PLAIN, NESTED_LOOP_MATERIALIZE, NESTED_LOOP_MEMOIZE |
| Partitionwise joins | PARTITIONWISE |
| Semijoin uniqueness | SEMIJOIN_UNIQUE, SEMIJOIN_NON_UNIQUE |
| Parallelism | GATHER, GATHER_MERGE, NO_GATHER |
Feed part of this snapshot back to the module, and it becomes a constraint:
SET pg_plan_advice.advice = 'JOIN_ORDER(f d)';
You do not need to copy the entire string back. The output shows which decisions the optimizer made. Select one or two that need constraints and leave the others unspecified, allowing the optimizer to decide freely. Which decision you constrain makes a substantial difference, as section 3 demonstrates.
3. Five experiments: what happens after adding constraints?
The environment consists of three containers on the same machine, all using official images:
| Instance | Port | Image | Core version |
|---|---|---|---|
pg18 | 5434 | postgres:18 | 18.7 |
pg19 | 5433 | postgres:19 | 19.0 |
ivorysql | 5432 / 1521 | ivorysql:5.6-ubi8 | 18.6 |
There are two test tables: join_fact, with 300,000 rows and no index on dim_id, and join_dim, with 200 rows and a primary key. Table names and queries follow the official Getting Started example to make comparison easy. I increased the fact table to 300,000 rows so cost differences would be visible.
Section 3.1 applies the same advice to two queries: one with WHERE f.v < 300, returning 299 rows, and a full join without WHERE, returning 300,000 rows. They differ by only one filter, yet lead to very different conclusions.
3.1 Change only join order: the plan changes, but the cost depends on volume
LOAD 'pg_plan_advice'; -- 环境已预加载,这里保留只为演示单会话用法
SET pg_plan_advice.advice = 'JOIN_ORDER(d f)';
EXPLAIN (COSTS OFF) SELECT * FROM join_fact f JOIN join_dim d
ON f.dim_id = d.id WHERE f.v < 300;
Merge Join
Merge Cond: (d.id = f.dim_id)
-> Sort
Sort Key: d.id
-> Seq Scan on join_dim d
-> Sort
Sort Key: f.dim_id
-> Gather
Workers Planned: 1
-> Parallel Seq Scan on join_fact f
Filter: (v < 300)
Supplied Plan Advice:
JOIN_ORDER(d f) /* matched */

Figure 2. The actual terminal session constrains the join order to drive from
d. Hash Join becomes Merge Join, with a Sort on each side, while the advice remainsmatched.
The advice is accepted and marked matched, but the plan changes shape completely: Hash Join disappears, replaced by Merge Join and two Sort nodes.
At first glance this looks worse: two additional sorts. Measured execution time tells a more nuanced story. The tables below correspond to the filtered and full-join queries respectively. Compare each query only with its own baseline; their result sizes differ by three orders of magnitude.
Query 1: WHERE f.v < 300 (299 result rows)
| Advice | Estimated cost | Execution time (median of three runs, same machine and query) |
|---|---|---|
| None | 4863.20 | 11.5 ms (baseline) |
JOIN_ORDER(d f) | 4883.64 | 10.5 ms (≈1.0×, within measurement noise) |
Query 2: full join (300,000 result rows)
| Advice | Estimated cost | Execution time (median of three runs, same machine and query) |
|---|---|---|
| None | 5433.69 | 55.5 ms (baseline) |
JOIN_ORDER(d f) | 14753.50 | 79.6 ms (≈1.4×) |
For query 1, cost rises only 0.4%, and execution stays at essentially the same level: 10.5 versus 11.5 ms, a difference within millisecond-scale noise. The plan shape changes completely, while performance barely moves.
For query 2, removing WHERE from the same tables and advice increases cost by 171% and execution time by about 40%. Execution varies with hardware and load, so compare ratios for the same query on the same machine, rather than absolute values.
The difference lies in what the advice actually constrains.
JOIN_ORDER(f d) is the optimizer's original choice: f is the outer input, while building a hash table for the 200-row d costs almost nothing. With JOIN_ORDER(d f), d becomes the driver and f is fixed on the inner side: the build or sort side, depending on whether Hash Join or Merge Join is selected. Hashing or sorting 300,000 rows is expensive. Without an index on dim_id, there is no cheaper Nested Loop with an inner index lookup available.
The filter WHERE f.v < 300 hides that cost because only 299 rows reach the join. Sorting 299 rows or hashing 200 rows takes less than a millisecond. The constraint still has a cost; the filter makes that cost negligible.
Why Merge Join? At 299 rows, its estimated cost is 4883.64, versus 4934.33 for Hash Join, about 1% lower. The optimizer chooses the cheaper estimate. The two alternatives are already close enough that a small difference decides the outcome.
This is what makes advice difficult to validate. On a small result set in development, it appears harmless. At full production volume, the same advice pushes the cost to nearly three times the baseline.
There is another subtlety: the full-table query switches back to Hash Join under JOIN_ORDER(d f):
Hash Join
Hash Cond: (d.id = f.dim_id)
-> Seq Scan on join_dim d
-> Hash
-> Seq Scan on join_fact f
Supplied Plan Advice:
JOIN_ORDER(d f) /* matched */
Merge Join is gone. Sorting 300,000 rows is too expensive, so the optimizer chooses hashing while respecting the fixed join order.
The advice fixes order, not method. What looks like a fixed plan is only a partially constrained plan; the rest still follows cost estimates.
3.2 A join-method constraint can also change join order
Express a similar intent differently: do not specify the order; just require f to be the inner, hash-building side.
SET pg_plan_advice.advice = 'HASH_JOIN(f)';
Hash Join
Hash Cond: (d.id = f.dim_id)
-> Seq Scan on join_dim d
-> Hash
-> Gather
Workers Planned: 1
-> Parallel Seq Scan on join_fact f
Filter: (v < 300)
Supplied Plan Advice:
HASH_JOIN(f) /* matched */
The plan now drives from d and builds the hash table from f. Notice that Hash Cond is reversed too: (d.id = f.dim_id), with d on the outer side.
Compare this with section 3.1: both aim to drive from d, yet the order constraint produces Merge Join, while the method constraint produces Hash Join with parallelism.
At full-table volume, however, the difference disappears. JOIN_ORDER(d f) and HASH_JOIN(f) produce the same plan, with exactly the same estimated cost, 14753.50. They converge only when the best candidate happens to be Hash Join. Their permitted candidate sets differ: HASH_JOIN(f) excludes Merge Join, while JOIN_ORDER(d f) does not.
The Merge Join in section 3.1 is therefore not an inevitable result of constraining join order. It happens because sorting is slightly cheaper at 299 rows. The same advice can produce different plans as the data volume changes.
Different constraint expressions leave the optimizer different room to maneuver. This mechanism defines a permitted range rather than issuing a complete instruction. The results coincide only when the best candidate inside each range happens to be the same.
3.3 Disabling parallelism has an immediate, visible effect
SET pg_plan_advice.advice = 'NO_GATHER(f d)';
Hash Join
Hash Cond: (f.dim_id = d.id)
-> Seq Scan on join_fact f
Filter: (v < 300)
-> Hash
-> Seq Scan on join_dim d
Supplied Plan Advice:
NO_GATHER(f) /* matched */
NO_GATHER(d) /* matched */
Gather disappears and the plan becomes single-process. This is immediately visible in the plan and is the most straightforward of the first four experiments.
3.4 Conflicting constraints produce feedback, not an error
Supply two contradictory constraints: require a sequential scan of f, but also require f to be absent from the final plan:
SET pg_plan_advice.advice = 'SEQ_SCAN(f) DO_NOT_SCAN(f)';
Hash Join
Hash Cond: (f.dim_id = d.id)
-> Gather
Workers Planned: 1
-> Parallel Seq Scan on join_fact f
Filter: (v < 300)
-> Hash
-> Seq Scan on join_dim d
Supplied Plan Advice:
SEQ_SCAN(f) /* matched, conflicting */
DO_NOT_SCAN(f) /* matched, conflicting, failed */

Figure 3. In the actual terminal output, two incompatible advice items are marked
conflicting; one also carriesfailed. The query still plans and runs without an error.
There is no error or interruption. The query plans and executes normally. The conflict becomes two annotations: one conflicting, the other both conflicting and failed.
This is a key distinction from hints. Hint conflicts may be silently ignored or reported as errors; plan advice records conflicts in the execution plan, where EXPLAIN makes them visible.
You still have to inspect that feedback. Neither of the following failure modes actively reports an error by default.
3.5 Identical SQL and advice, different data distribution: the plan drifts
The first four experiments keep SQL fixed and vary advice. To substantiate the title, another experiment is needed: keep every character of SQL and advice unchanged, alter only the data distribution and statistics, and see whether the plan drifts.
This resembles a real incident: a statement runs well at deployment, nobody changes it, the advice remains in place, and the plan later changes as the data distribution shifts.
I used the same 300,000-row join_fact and join_dim structure in a separate drift_test database to avoid changing the earlier baselines. The query always includes WHERE f.v < 300. Two fixed advice strings are tested separately: NO_GATHER(f d) and JOIN_ORDER(f d). The only variable is the distribution of v, specifically how many rows satisfy v < 300:
-- 阶段 A:初始,v<300 命中 299 行
-- 阶段 B:把 20 万行的 v 改成 1,重新 ANALYZE,v<300 命中 200000 行
UPDATE join_fact SET v = 1 WHERE id <= 200000;
ANALYZE join_fact;
The SQL and advice are identical in phases A and B; only the data distribution changes:
Advice (matched in both phases) | Phase A: 299 rows satisfy v<300 | Phase B: 200,000 rows satisfy v<300 |
|---|---|---|
NO_GATHER(f d) | Nested Loop + Index Scan; NO_GATHER(f) /* matched */ and NO_GATHER(d) /* matched */ | Hash Join + Seq Scan; both advice items still matched |
JOIN_ORDER(f d) | Hash Join + parallel Gather (Workers Planned: 2); JOIN_ORDER(f d) /* matched */ | Hash Join + serial Seq Scan, without Gather; advice still matched |
Phase A plan with NO_GATHER(f d):
Nested Loop
-> Seq Scan on join_fact f
Filter: (v < 300)
-> Index Scan using join_dim_pkey on join_dim d
Index Cond: (id = f.dim_id)
Supplied Plan Advice:
NO_GATHER(f) /* matched */
NO_GATHER(d) /* matched */
Phase B, with the same SQL and advice:
Hash Join
Hash Cond: (f.dim_id = d.id)
-> Seq Scan on join_fact f
Filter: (v < 300)
-> Hash
-> Seq Scan on join_dim d
Supplied Plan Advice:
NO_GATHER(f) /* matched */
NO_GATHER(d) /* matched */
NO_GATHER(f d) constrains only parallelism. Neither plan has Gather, so both correctly report matched. The join method nevertheless changes from Nested Loop to Hash Join. The optimizer recalculates decisions outside the constraint's scope using the new distribution.
JOIN_ORDER(f d) makes the point even more directly. Both phases report JOIN_ORDER(f d) /* matched */, but phase A uses parallel Gather and phase B uses serial Seq Scan. Join order stays fixed while parallelism changes with data volume.
This demonstrates the title's claim: matched means that the supplied constraint was respected in this planning operation, not that the plan is identical to the previous one. When data distribution changes, the optimizer chooses again within the permitted range. The resulting plan can be completely different while all advice still says matched. To detect plan drift, monitor the execution plans themselves as well as advice feedback. This is both the improvement over hints, through readable feedback, and the reason advice cannot replace plan baselines: the feedback describes constraints, not stability.
4. Six feedback states, beyond “applied” or “not applied”
Taken together, the experiments illustrate the complete set of feedback states:
| State | Meaning | Example |
|---|---|---|
matched | All targets were observed and the advice matched | Normal case |
partially matched | Some targets were observed, or they did not appear together | Invalid join order (documentation example, not tested here); nonexistent alias (tested here) |
not matched | No targets were observed | Advice does not correspond to the query |
inapplicable | The requested tag cannot be applied | Nonexistent index (tested here); semijoin advice for a non-semijoin (documentation example, not tested here) |
conflicting | Two advice items require mutually exclusive behavior | Section 3.4 |
failed | The final plan did not follow this advice | Appears only on an item also marked matched |
Every item has exactly one of matched, partially matched, or not matched; the other three are additional flags. Multi-target advice such as HASH_JOIN(f d) is split into separate HASH_JOIN(f) and HASH_JOIN(d) feedback lines. JOIN_ORDER(f d) remains a single item.
Another test requests an index that does not exist:
SET pg_plan_advice.advice = 'INDEX_SCAN(f no_such_idx)';
Supplied Plan Advice:
INDEX_SCAN(f no_such_idx) /* matched, inapplicable, failed */
Three flags appear together: the target was found (matched), the tag could not apply (inapplicable), and the final plan did not follow it (failed). As in section 3.4, no error is raised.
Another failure is easier to overlook. The How It Works documentation shows a three-table query with a misspelled alias x in JOIN_ORDER(x f d), resulting in Nested Loop, Disabled: true, and partially matched. It notes that the outcome is usually worse than supplying no advice. Here I reproduce a two-table version and test a detail the documentation example does not explore: feedback_warnings is off by default, leaving the application unaware. Misspell the table alias:
SET pg_plan_advice.advice = 'JOIN_ORDER(x f)';
EXPLAIN (COSTS OFF) SELECT * FROM join_fact f JOIN join_dim d
ON f.dim_id = d.id WHERE f.v < 300;
Gather
Workers Planned: 1
-> Nested Loop
Disabled: true
-> Parallel Seq Scan on join_fact f
Filter: (v < 300)
-> Index Scan using join_dim_pkey on join_dim d
Index Cond: (id = f.dim_id)
Supplied Plan Advice:
JOIN_ORDER(x f) /* partially matched */
Notice three things.
First, there is no error. Alias x does not exist, but the query still plans and executes.
Second, the plan changes. The original Hash Join becomes Nested Loop with Disabled: true. Although partially matched sounds like partial success, the optimizer has been led toward a disabled path and then has to use it.
Third, no warning is emitted by default. pg_plan_advice.feedback_warnings defaults to false. Enable it, and the same statement produces:
WARNING: supplied plan advice was not enforced
DETAIL: advice JOIN_ORDER(x f) feedback is "partially matched"
Enable this setting when configuring advice for the first time. Otherwise, incorrectly supplied advice and no advice at all look the same to the application. Only a deliberate EXPLAIN reveals the difference, and during an incident few people immediately think to explain a query that previously worked well.
The mechanism addresses a frustrating limitation of the hint workflow: you can inspect whether advice was enforced without inferring it from the shape of the plan.
5. Persisting advice with stash and query_id
Manual SET applies only to the current session. Production cannot rely on setting it every time. Persistence is provided by pg_stash_advice.
The query identifier is the key: each SQL statement has a query_id, which is used to look up its advice.
Obtain the identifier through EXPLAIN VERBOSE:
pg19=# EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM join_fact f
JOIN join_dim d ON f.dim_id = d.id WHERE f.v < 300;
...
Query Identifier: -6097915719339146261
Store it:
CREATE EXTENSION pg_stash_advice;
SELECT pg_create_advice_stash('s1');
SELECT pg_set_stashed_advice('s1', -6097915719339146261, 'HASH_JOIN(f)');
SET pg_stash_advice.stash_name = 's1';
There are six supporting functions: create a stash, drop a stash, write advice (pass NULL to delete an entry), list all stashes, list a stash's contents, and manually start the persistence worker.
Three results are worth remembering.
First, stashes live in dynamic shared memory but are persisted to disk and can survive restart. pg_stash_advice.persist defaults to on. The background worker checks for changes at persist_interval, defaulting to 30 seconds, and writes pg_stash_advice.tsv in the data directory. In my test, after creating two advice entries and running docker restart, pg_get_advice_stashes() still returned s1 / 2. Both query IDs and advice strings were unchanged, and the pg_stash_advice worker process started automatically.
The conditions matter. The documentation says the worker starts automatically only when pg_stash_advice is in shared_preload_libraries at startup and persist = true. A worker started manually with pg_start_stash_advice_worker() writes to disk but does not read from it. My first test had a broken configuration and a container restart loop, with zero entries visible. Persistence had not failed: the worker had never started.
Second, the comma-separated value of shared_preload_libraries must be enclosed in single quotes. Writing shared_preload_libraries=pg_plan_advice,pg_stash_advice without quotes causes configuration parsing to fail and prevents startup:
LOG: syntax error in file ".../postgresql.conf" line 934, near token ","
FATAL: configuration file ".../postgresql.conf" contains errors
This can look like a container restart loop, with only a syntax error in the logs, and is easy to mistake for an image problem.
Third, automatic application works, provided the query_id is copied exactly. In my first test, the stored identifier differed by one digit from the value returned by EXPLAIN VERBOSE: a digit had been omitted. EXPLAIN kept returning the unconstrained Hash Join, without Supplied Plan Advice or any error. Once the query ID was corrected, the same HASH_JOIN(f) was applied automatically and changed the plan:
Supplied Plan Advice:
HASH_JOIN(f) /* matched */

Figure 4. The actual terminal session shows
HASH_JOIN(f)from stashs1applied automatically. The plan drives fromd, builds the hash table fromf, reversesHash Condto(d.id = f.dim_id), and marks the advicematched.
This is more subtle than incorrect advice: one wrong digit in query_id yields no error or warning, only a permanent silent mismatch. Copy the identifier exactly from the Query Identifier: line in EXPLAIN VERBOSE, including the minus sign; do not transcribe it from memory. Manual SET does not depend on query_id and was used successfully in all four initial experiments. For automatic stash application, copying the ID correctly is the first step.
Consider two operational details beforehand. Source precedence: advice in the pg_plan_advice.advice GUC may coexist with a stash entry. The official documentation does not explicitly state which takes precedence, so use one source per statement to avoid changing one while the other remains active. Rollback: remove a stash entry by passing NULL to pg_set_stashed_advice; for GUC-based advice, use RESET pg_plan_advice.advice. Include these actions in the change procedure instead of searching for them during an incident.
6. Comparing it with Oracle SQL Plan Baseline
The goals overlap, but the approaches differ:
| Dimension | Oracle SPM | PG 19 plan advice |
|---|---|---|
| What it manages | Plan objects: store generated plans as baselines | Plan constraints: express optimizer decisions as advice |
| Storage | Inside the database, in the SQL Management Base | Strings in SQL files, settings, or a DSM stash |
| Granularity | Multiple accepted plans per SQL statement | One advice set per statement, optionally constraining only selected decisions |
| How new plans take over | Evolution; acceptance is required to enter the baseline | Not managed; decisions outside the constraints remain free |
| Constraint strength | Strong: plans outside the baseline are not selected | Weaker: choices remain limited to candidates the optimizer considers feasible |
| Failure visibility | Compare the baseline with the execution plan | EXPLAIN annotates matched, failed, and conflicting directly |
| Can it enforce a plan the optimizer would not currently choose? | It can preserve an already generated plan whose current cost is higher, but cannot create a plan the optimizer never considers | No; this is an explicit documented limitation |
The first and last rows describe the fundamental difference. The others concern implementation.
SPM manages the result: it stores completed plans and lets the optimizer choose among them. Plan advice manages the process: it constrains planning, but the plan is still calculated at that moment.
SPM can therefore keep a statement on a stored plan in a way that plan advice cannot. If the optimizer considers the requested plan infeasible, advice permits a different plan and reports failed. Conversely, plan advice is lighter: no plan objects or evolution workflow are needed. A single string can express “keep the join order, decide the rest yourself.”
The appropriate choice depends on whether you need the exact same plan or simply want to prevent particular bad decisions.
7. What IvorySQL users can do today
The conclusion is direct: IvorySQL 5.6 cannot use this module. Its core must first move to PG 19.
Attempt to load it in 5.6's Oracle mode on port 1521:
$ docker exec ivorysql psql -h 127.0.0.1 -p 1521 -U ivorysql \
-c "LOAD 'pg_plan_advice'"
ERROR: could not access file "pg_plan_advice": No such file or directory
The error is expected: 5.6 uses an 18.6 core, while this module arrives in 19. PG mode on port 5432 fails identically:
$ docker exec ivorysql psql -h 127.0.0.1 -p 5432 -U ivorysql \
-c "LOAD 'pg_plan_advice'"
ERROR: could not access file "pg_plan_advice": No such file or directory
Both modes report the same error. This is a core-version issue, independent of the parser.
It agrees with an earlier comparison of the dual-parser design: dual parsers operate at the syntax layer; they do not determine which core capabilities exist. Oracle-style parsing does not add Oracle functionality by itself.
There are two options in the meantime.
First, pg_hint_plan. It is the most direct option, commonly placing hints in SQL comments:
/*+ NestLoop(f d) */ SELECT * FROM join_fact f JOIN join_dim d ...
The trade-offs were discussed earlier. The common comment-based form ties hints to SQL, so changing hints requires changing SQL. Hint Table avoids that coupling but must be enabled separately. Feedback is not emitted by default; configure debug_print and inspect logs. Revalidate hint syntax after major-version upgrades.
Second, reduce drift using existing mechanisms. Raise statistics targets, choose plan_cache_mode deliberately for critical queries, and split fragile SQL into smaller statements. These measures do not freeze plans, but can reduce the likelihood of regressions.
Direct use becomes possible only when the core reaches 19 and pg_plan_advice is included in the distribution. Good initial candidates are reporting queries that run well today but may regress unpredictably: they run for a long time, usually have a consistent plan shape, and affect users immediately when that shape changes.
8. When not to use it
The mechanism has clear boundaries. Misusing it can be worse than leaving planning unconstrained.
Advice adds planning overhead. Constraints must be parsed, matched, and checked at each planning operation; generating feedback also costs resources. The documentation for always_store_advice_details explicitly warns of this overhead and recommends enabling it only in sessions that need it. Advice is therefore most useful for infrequent critical SQL requiring predictable plans. Applying it broadly to frequent small queries may cost more in planning than it saves.
Avoid constraining tables whose distributions change substantially. A constraint is valuable only while the preferred plan remains good. If volume doubles or skew changes tomorrow, that constraint can become a liability. The full-table experiment in section 3.1 already shows the effect: fixing join order alone increases cost from 5433.69 to 14753.50.
The most detailed constraints are usually not the best choice. Selecting two relevant items is safer than copying all five lines. The official documentation likewise recommends keeping only the decisions you actually want to control.
Aggregates and set operations are outside its scope. Choosing HashAgg versus GroupAgg or controlling UNION is not currently covered. Their plan stability requires other approaches.
Above geqo_threshold, defaulting to 12 joined relations, results become probabilistic. GEQO uses randomized search, so even a compliant plan is not guaranteed to be found. Light join-order constraints can usually still be satisfied. Consider statement-scoped SET geqo = off only for heavier constraints that require reliable enforcement. Do not disable it globally, as planning time for queries joining more than 12 tables can grow sharply. Scan advice is unaffected because it does not alter join order.
The same join-order constraint can have vastly different effects. In section 3.1, JOIN_ORDER raises cost by only 0.4% on the small result set, with almost unchanged execution time. On the full join, cost becomes 2.7 times the baseline and execution takes about 40% longer. Validate advice with realistic volumes; conclusions from small development tables do not transfer reliably.
A misspelled alias can be worse than no advice. It raises no error, silently changes the plan, and can produce Disabled: true, while feedback_warnings is off by default. Enable warnings and make inspection of each item's matched status part of deployment checks instead of waiting for a regression.
Three GUCs also determine whether the feedback is visible.
pg_plan_advice.always_store_advice_details defaults to false. While planning a prepared statement, the module cannot know whether an EXPLAIN will follow. To save overhead, advice and feedback are not generated by default, so EXPLAIN EXECUTE has no Supplied Plan Advice section. My test found the same with EXPLAIN (PLAN_ADVICE) EXECUTE, because nothing had been stored. Prepared statements are common in production; enabling this parameter in the relevant sessions is necessary to make feedback inspection practical.
pg_plan_advice.always_explain_supplied_advice defaults to true. This explains why sections 3.1–3.4 show Supplied Plan Advice with EXPLAIN (COSTS OFF) even without PLAN_ADVICE. It is the default behavior, not a copying mistake. Set it to false to display feedback only with EXPLAIN (PLAN_ADVICE).
compute_query_id matters for stashes. If it is off, query identifiers are not generated and automatic application silently never matches. This resembles the incorrect digit in section 5, but affects the whole matching mechanism rather than one entry.
Finally, constraints apply at planning time only. Changing advice does not immediately replan cached prepared statements or statements in PL/pgSQL. Use DISCARD PLANS or reconnect to observe the change.
Appendix: test environment
| Item | Details |
|---|---|
| PG 19.0 | postgres:19, Debian 19.0-1.pgdg13+1, port 5433 |
| PG 18.7 | postgres:18, port 5434 |
| IvorySQL 5.6 | ivorysql:5.6-ubi8, core 18.6, ports 5432 / 1521 |
| Test data | 300,000 rows in join_fact, 200 in join_dim; planned after ANALYZE |
| Comparison | Filtered query WHERE f.v < 300 (299 rows) and full join (300,000 rows); median of three runs each |
| Section 3.5 drift test | Separate drift_test database with identical table structures; UPDATE and ANALYZE change the v<300 match count from 299 to 200000, leaving SQL and advice unchanged |
| Module loading | shared_preload_libraries = 'pg_plan_advice,pg_stash_advice' |
All EXPLAIN output in this article comes from actual docker exec pg19 psql executions on 192.168.3.110. The four screenshots show the MobaXterm desktop terminal, including command echoes and row counts. Before reproducing the tests, ensure pg_stash_advice.stash_name is empty. It had previously been set to s1 in my environment; stash entries overrode session-level SET pg_plan_advice.advice, making the setting appear ineffective. An empty string disables automatic application. Each experiment in sections 3.1–3.4 can be repeated in order. Advice strings may vary slightly with statistics, but the two observed behaviors—constraints changing plans and conflicts appearing as annotations—remain consistent. Execution time varies by machine; ratios matter more than absolute values.
About IvorySQL
IvorySQL is an open-source, Oracle-compatible PostgreSQL database led by Highgo. Its dual-parser architecture maintains full compatibility with native PostgreSQL and supports its ecosystem of tools and extensions while providing additional, flexible Oracle compatibility features.
- Website: https://ivorysql.org/en
- GitHub: https://github.com/IvorySQL/IvorySQL
- Community: search for
ivorysql_officialon WeChat and contact the community assistant to join. - Online trial: http://trial.ivorysql.org:8080/
Related Posts
Try IvorySQL
Get started with IvorySQL today. Read the docs or try our online demo.


