DEV Community

Vahid Yousefzadeh
Vahid Yousefzadeh

Posted on

PostgreSQL 19: pg_plan_advice and pg_stash_advice

In my previous article, PostgreSQL vs Oracle: When Higher Cost Means Better Performance, I showed that a plan with a higher estimated cost can run almost twice as fast as the plan the optimizer prefers. To demonstrate this, we had to use SET enable_seqscan = off, which disables sequential scans for all tables in the session.
PostgreSQL 19 adds two contrib modules that remove that limitation:
pg_plan_advice allows us to guide PostgreSQL toward a particular execution plan without changing the original SQL statement. For example, we can ask the planner to use an index scan instead of a sequential scan.
pg_stash_advice takes this a step further by allowing us to save plan advice for a specific query. PostgreSQL can then automatically apply that advice whenever the query is executed.
In simple terms, pg_plan_advice guides PostgreSQL toward a specific execution plan, while pg_stash_advice allows you to save and automatically reuse that advice.
In this article, we will demonstrate both modules using a table with 100 million rows and compare the execution plans and performance.
In this article I repeat the same experiment with both modules.

1. Test setup

The table has 100 million rows in which only one row is VIP and every other row is REGULAR, so the data is extremely skewed. A B-tree index on customer_type is the only index.

vahiddb=# CREATE TABLE tbl_test (
    id             BIGINT,
    customer_type  VARCHAR(20),
    city           VARCHAR(30),
    status         VARCHAR(20)
);
CREATE TABLE
Enter fullscreen mode Exit fullscreen mode
vahiddb=# INSERT INTO tbl_test (id, customer_type, city, status)
SELECT
    gs,
    CASE WHEN gs = 100000000 THEN 'VIP' ELSE 'REGULAR' END,
    CASE (gs % 10)
        WHEN 0 THEN 'Babol'  WHEN 1 THEN 'Amol'      WHEN 2 THEN 'Behshahr'
        WHEN 3 THEN 'MarziKola' WHEN 4 THEN 'Bandpay' WHEN 5 THEN 'DerazKesh'
        WHEN 6 THEN 'Sari'   WHEN 7 THEN 'Rasht'     WHEN 8 THEN 'Zanjan'
        ELSE 'Tel Aviv'
    END,
    CASE
        WHEN gs % 100 < 95 THEN 'ACTIVE'
        WHEN gs % 100 < 99 THEN 'INACTIVE'
        ELSE 'SUSPENDED'
    END
FROM generate_series(1, 100000000) AS gs;
INSERT 0 100000000
Enter fullscreen mode Exit fullscreen mode
vahiddb=# CREATE INDEX idx_customer_type ON tbl_test(customer_type);
CREATE INDEX
Enter fullscreen mode Exit fullscreen mode
vahiddb=# VACUUM ANALYZE tbl_test;
VACUUM
Enter fullscreen mode Exit fullscreen mode

2. Examining the Default Execution Plan

Without any advice, PostgreSQL chooses a Parallel Seq Scan and the query takes 23.4 seconds.

vahiddb=# EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';

                                                                       QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=1383576.41..1383576.42 rows=1 width=8) (actual time=23365.759..23366.962 rows=1.00 loops=1)
   Buffers: shared hit=15746 read=741830
   ->  Gather  (cost=1383576.20..1383576.41 rows=2 width=8) (actual time=23365.752..23366.957 rows=3.00 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         Buffers: shared hit=15746 read=741830
         ->  Partial Aggregate  (cost=1382576.20..1382576.21 rows=1 width=8) (actual time=23358.505..23358.506 rows=1.00 loops=3)
               Buffers: shared hit=15746 read=741830
               ->  Parallel Seq Scan on tbl_test  (cost=0.00..1278409.50 rows=41666680 width=0) (actual time=2.840..16949.465 rows=33333333.00 loops=3)
                     Filter: ((customer_type)::text = 'REGULAR'::text)
                     Rows Removed by Filter: 0
                     Buffers: shared hit=15746 read=741830
 Planning Time: 0.062 ms
 Execution Time: 23366.986 ms
(14 rows)
Enter fullscreen mode Exit fullscreen mode

3. The old way: enable_seqscan = off

Turning off sequential scans forces a Parallel Index Only Scan. The estimated cost rises to 1,610,214, yet the query finishes in 14.2 seconds.

vahiddb=# SET enable_seqscan = off;
SET

vahiddb=# EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';
                                                                                      QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=1610214.52..1610214.53 rows=1 width=8) (actual time=14213.893..14218.250 rows=1.00 loops=1)
   Buffers: shared hit=52 read=84199 written=1516
   ->  Gather  (cost=1610214.31..1610214.52 rows=2 width=8) (actual time=14213.524..14218.243 rows=3.00 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         Buffers: shared hit=52 read=84199 written=1516
         ->  Partial Aggregate  (cost=1609214.31..1609214.32 rows=1 width=8) (actual time=14207.302..14207.303 rows=1.00 loops=3)
               Buffers: shared hit=52 read=84199 written=1516
               ->  Parallel Index Only Scan using idx_customer_type on tbl_test  (cost=0.57..1505047.61 rows=41666680 width=0) (actual time=2.497..8583.733 rows=33333333.00 loops=3)
                     Index Cond: (customer_type = 'REGULAR'::text)
                     Heap Fetches: 0
                     Index Searches: 1
                     Buffers: shared hit=52 read=84199 written=1516
 Planning Time: 0.192 ms
 Execution Time: 14218.301 ms
(15 rows)
Enter fullscreen mode Exit fullscreen mode

The index is far smaller than the table, so the scan reads about 84,000 pages instead of about 757,000. The problem with this approach is its scope: enable_seqscan applies to the whole session and every table in it.

4. The new way: pg_plan_advice

pg_plan_advice is a contrib module that needs no CREATE EXTENSION; you load it as a library. Once loaded, EXPLAIN accepts a PLAN_ADVICE option that prints the advice string describing the chosen plan.

vahiddb=#  LOAD 'pg_plan_advice';
LOAD

vahiddb=# EXPLAIN (ANALYZE, BUFFERS, PLAN_ADVICE)
SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';

                                                                       QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=1383576.41..1383576.42 rows=1 width=8) (actual time=22456.603..22457.786 rows=1.00 loops=1)
   Buffers: shared hit=564 read=757012
   ->  Gather  (cost=1383576.20..1383576.41 rows=2 width=8) (actual time=22452.917..22457.780 rows=3.00 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         Buffers: shared hit=564 read=757012
         ->  Partial Aggregate  (cost=1382576.20..1382576.21 rows=1 width=8) (actual time=22446.574..22446.575 rows=1.00 loops=3)
               Buffers: shared hit=564 read=757012
               ->  Parallel Seq Scan on tbl_test  (cost=0.00..1278409.50 rows=41666680 width=0) (actual time=0.943..16249.226 rows=33333333.00 loops=3)
                     Filter: ((customer_type)::text = 'REGULAR'::text)
                     Rows Removed by Filter: 0
                     Buffers: shared hit=564 read=757012
 Planning:
   Buffers: shared hit=48 read=22
 Planning Time: 9.715 ms
 Generated Plan Advice:
   SEQ_SCAN(tbl_test)
   GATHER(tbl_test)
 Execution Time: 22457.857 ms
(19 rows)
Enter fullscreen mode Exit fullscreen mode

PostgreSQL generates advice for the selected plan. In this experiment, the generated advice includes:
SEQ_SCAN(tbl_test)
GATHER(tbl_test)

This describes the planner's chosen sequential scan and parallel execution strategy.

Applying INDEX_ONLY_SCAN advice

Now let's guide the planner toward the index-only scan:

vahiddb=# SET pg_plan_advice.advice = 'INDEX_ONLY_SCAN(tbl_test idx_customer_type)';
SET
Enter fullscreen mode Exit fullscreen mode

Execute the query again:

vahiddb=# EXPLAIN (ANALYZE, BUFFERS, PLAN_ADVICE)
SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';

                                                                                      QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=1610214.52..1610214.53 rows=1 width=8) (actual time=14171.678..14194.537 rows=1.00 loops=1)
   Buffers: shared hit=48 read=84203
   ->  Gather  (cost=1610214.31..1610214.52 rows=2 width=8) (actual time=14168.515..14194.529 rows=3.00 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         Buffers: shared hit=48 read=84203
         ->  Partial Aggregate  (cost=1609214.31..1609214.32 rows=1 width=8) (actual time=14163.794..14163.795 rows=1.00 loops=3)
               Buffers: shared hit=48 read=84203
               ->  Parallel Index Only Scan using idx_customer_type on tbl_test  (cost=0.57..1505047.61 rows=41666680 width=0) (actual time=1.852..8594.008 rows=33333333.00 loops=3)
                     Index Cond: (customer_type = 'REGULAR'::text)
                     Heap Fetches: 0
                     Index Searches: 1
                     Buffers: shared hit=48 read=84203
 Planning:
   Buffers: shared hit=6
 Planning Time: 0.306 ms
 Supplied Plan Advice:
   INDEX_ONLY_SCAN(tbl_test idx_customer_type) /* matched */
 Generated Plan Advice:
   INDEX_ONLY_SCAN(tbl_test public.idx_customer_type)
   GATHER(tbl_test)
 Execution Time: 14194.594 ms
(22 rows)
Enter fullscreen mode Exit fullscreen mode

Three things are new compared with enable_seqscan = off:

  • Scope: the advice names one table and one index, so nothing else in the session is affected.
  • Feedback: /* matched */ confirms the planner actually followed the advice. An advice string that cannot be applied is reported instead of failing silently.
  • Same plan, same cost: the result is identical to the old way (cost 1,610,214.52, 14.2 seconds), which shows the advice only steers the planner and does not change execution. When finished, RESET pg_plan_advice.advice; restores the default behavior.
vahiddb=# RESET pg_plan_advice.advice;
RESET
Enter fullscreen mode Exit fullscreen mode

5.Making it permanent: pg_stash_advice

A SET lasts only for one session. pg_stash_advice stores advice in a named stash, keyed by query identifier, and applies it automatically whenever that query is planned. Applications do not need to change.
First I need the query identifier, which requires compute_query_id:

vahiddb=# SET compute_query_id = on;
SET
vahiddb=# EXPLAIN (VERBOSE, COSTS OFF)
SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';
                                   QUERY PLAN
--------------------------------------------------------------------------------
 Finalize Aggregate
   Output: count(*)
   ->  Gather
         Output: (PARTIAL count(*))
         Workers Planned: 2
         ->  Partial Aggregate
               Output: PARTIAL count(*)
               ->  Parallel Seq Scan on public.tbl_test
                     Output: id, customer_type, city, status
                     Filter: ((tbl_test.customer_type)::text = 'REGULAR'::text)
 Query Identifier: -6414028140764465304
(11 rows)
Enter fullscreen mode Exit fullscreen mode

Then I create the extension and a stash, attach the advice to that identifier, and point the session at the stash:

vahiddb=# CREATE EXTENSION pg_stash_advice;
CREATE EXTENSION

vahiddb=# SELECT pg_create_advice_stash('vahid_stash');
 pg_create_advice_stash
------------------------

(1 row)

vahiddb=# SELECT pg_set_stashed_advice('vahid_stash', -6414028140764465304,'INDEX_ONLY_SCAN(tbl_test idx_customer_type)');
 pg_set_stashed_advice
-----------------------

(1 row)

vahiddb=# SET pg_stash_advice.stash_name = 'vahid_stash';
SET
Enter fullscreen mode Exit fullscreen mode

Execute the original query again:

vahiddb=# EXPLAIN (ANALYZE, BUFFERS, PLAN_ADVICE)
SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';
                                                                                      QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=1610214.52..1610214.53 rows=1 width=8) (actual time=13451.746..13456.091 rows=1.00 loops=1)
   Buffers: shared hit=48 read=84203
   ->  Gather  (cost=1610214.31..1610214.52 rows=2 width=8) (actual time=13451.556..13456.085 rows=3.00 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         Buffers: shared hit=48 read=84203
         ->  Partial Aggregate  (cost=1609214.31..1609214.32 rows=1 width=8) (actual time=13434.650..13434.650 rows=1.00 loops=3)
               Buffers: shared hit=48 read=84203
               ->  Parallel Index Only Scan using idx_customer_type on tbl_test  (cost=0.57..1505047.61 rows=41666680 width=0) (actual time=0.335..8024.294 rows=33333333.00 loops=3)
                     Index Cond: (customer_type = 'REGULAR'::text)
                     Heap Fetches: 0
                     Index Searches: 1
                     Buffers: shared hit=48 read=84203
 Planning Time: 0.091 ms
 Supplied Plan Advice:
   INDEX_ONLY_SCAN(tbl_test idx_customer_type) /* matched */
 Generated Plan Advice:
   INDEX_ONLY_SCAN(tbl_test public.idx_customer_type)
   GATHER(tbl_test)
 Execution Time: 13456.119 ms
(20 rows)
Enter fullscreen mode Exit fullscreen mode

I did not set pg_plan_advice.advice this time, yet the plan changes and the advice is reported as matched. The query took 13.5 seconds:

Supplied Plan Advice:
   INDEX_ONLY_SCAN(tbl_test idx_customer_type) /* matched */
 Generated Plan Advice:
   INDEX_ONLY_SCAN(tbl_test public.idx_customer_type)
   GATHER(tbl_test)
 Execution Time: 13456.119 ms
Enter fullscreen mode Exit fullscreen mode

Now the challenge is that when we exit the session, the setting will be ignored:

vahiddb=# exit
[postgres@OEL98-PG ~]$ psql
psql (19.0)
Type "help" for help.

postgres=# \c vahiddb
You are now connected to database "vahiddb" as user "postgres".
vahiddb=# \timing on
Timing is on.
vahiddb=# SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';
  count
----------
 99999999
(1 row)

Time: 20086.843 ms (00:20.087)
Enter fullscreen mode Exit fullscreen mode

6.Applying a Stash to an Entire Database

A stash is normally applied at the session level. This means every new connection would need to set the stash name manually.
To avoid this, we can configure the stash at the database level. This ensures that new sessions connecting to the database automatically use the specified stash.
First, add the required modules to shared_preload_libraries:

vahiddb=# ALTER SYSTEM SET shared_preload_libraries = 'pg_plan_advice', 'pg_stash_advice';
ALTER SYSTEM
Enter fullscreen mode Exit fullscreen mode

Restart PostgreSQL to apply the change:

[postgres@OEL98-PG data]$  pg_ctl -D /var/lib/pgsql/19/data -l logfile restart
waiting for server to shut down.... done
server stopped
waiting for server to start.... done
server started
Enter fullscreen mode Exit fullscreen mode

Next, configure the stash for the target database:

vahiddb=# ALTER DATABASE vahiddb SET pg_stash_advice.stash_name = 'vahid_stash';
ALTER DATABASE
Enter fullscreen mode Exit fullscreen mode

Reconnect to vahiddb and verify the setting:

vahiddb=# SHOW pg_stash_advice.stash_name;
 pg_stash_advice.stash_name
----------------------------
 vahid_stash
(1 row)
Enter fullscreen mode Exit fullscreen mode

We can also verify that the stash contains the expected advice:

vahiddb=# SELECT * FROM pg_get_advice_stash_contents('vahid_stash');
 stash_name  |       query_id       |                advice_string
-------------+----------------------+---------------------------------------------
 vahid_stash | -6414028140764465304 | INDEX_ONLY_SCAN(tbl_test idx_customer_type)
(1 row)
Enter fullscreen mode Exit fullscreen mode

Finally, execute the query without setting the advice manually:

vahiddb=# SELECT COUNT(*) FROM tbl_test WHERE customer_type = 'REGULAR';

  count
----------
 99999999
(1 row)
Time: 13289.901 ms (00:13.290)
Enter fullscreen mode Exit fullscreen mode

The stash name applies to new sessions in that database, while existing sessions keep their current value.
Dropping the stash is enough to bring the original plan back:

vahiddb=# SELECT pg_drop_advice_stash('vahid_stash');
 pg_drop_advice_stash
----------------------

(1 row)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)