steering the planner
postgres has no hints. enable_* switches, cost settings, query rewrites, and what you can actually control.
- address
- everything.optimizer.steering_the_planner
- part
- part 10, the optimizer
- chapter
- chapter 10 of 10
- reading time
- 7 min
core postgres has no query hints. you can't write "use this index" next to a query. what you can change are the planner's inputs: statistics, cost settings, the enable_* switches, and the shape of the query itself, at the level of a server, a tablespace, a database, a role, a function, a session or a single transaction.
the switches don't forbid anything: postgres 18 just avoids disabled plans when it has another choice, and prints Disabled: true when it doesn't.
the picture
you know how other databases let you write /*+ INDEX(orders) */ and postgres people tell you to fix your statistics instead? it's a deliberate choice: a hint is frozen while the data changes, and postgres would rather you fix what made the planner wrong.
think of a sat-nav. you can't tell it "take this road" (no hints). you can tell it a road is closed (an enable_* switch), that tolls are expensive (a cost setting), give it a better map (statistics), or pick a different destination that means the same (a rewrite). it still picks the route.
here's what the switches do to one join:
- Hash Join (cost=49.83..259.13 rows=330 width=20)
- Hash Cond: (o.customer_id = c.id)
- -> Seq Scan on orders o (cost=0.00..183.00 rows=10000 width=12)
- -> Hash (cost=49.00..49.00 rows=66 width=16)
- -> Seq Scan on customers c (cost=0.00..49.00 rows=66 width=16)
- Filter: (city = 'Paris'::text)
nothing turned off: a hash join, the cheapest plan.
the enable_* switches
SELECT name, setting FROM pg_settings WHERE name LIKE 'enable%' ORDER BY name;| nametext | settingtext |
|---|---|
| enable_async_append | on |
| enable_bitmapscan | on |
| enable_distinct_reordering | on |
| enable_gathermerge | on |
| enable_group_by_reordering | on |
| enable_hashagg | on |
| enable_hashjoin | on |
| enable_incremental_sort | on |
| enable_indexonlyscan | on |
| enable_indexscan | on |
| enable_material | on |
| enable_memoize | on |
| enable_mergejoin | on |
| enable_nestloop | on |
| enable_parallel_append | on |
| enable_parallel_hash | on |
| enable_partition_pruning | on |
| enable_partitionwise_aggregate | off |
| enable_partitionwise_join | off |
| enable_presorted_aggregate | on |
one per plan node type or technique: scans (seqscan, indexscan, indexonlyscan, bitmapscan, tidscan), joins (nestloop, hashjoin, mergejoin), sorts and aggregation (sort, incremental_sort, hashagg), memoize, material, parallel plans, partition pruning and partitionwise joins, and a few more.
turning one off doesn't remove the option. before postgres 18, a disabled path got a huge cost penalty (1e10). since 18, the planner counts disabled nodes in each path and compares that count before cost, so a plan with fewer disabled nodes always wins, and when every option is disabled you still get the cheapest of them, with Disabled: true on the nodes that broke the rule:
SET enable_seqscan = off;
EXPLAIN SELECT * FROM products WHERE name = 'left-handed teapot';
RESET enable_seqscan;no index on name, so there's nothing else to do but read the table, and the plan says so.
the switches are a diagnostic: "what would the plan be without a hash join, and how much worse does postgres think it is?" they're too blunt for production, because they apply to every join in every query of the session.
SET enable_indexscan = off;
EXPLAIN SELECT * FROM orders WHERE id = 42;SET enable_indexscan = off;
EXPLAIN SELECT * FROM orders WHERE id = 42;
RESET enable_indexscan;cost settings, at the right level
the cost model's settings describe hardware, and every one can be set at the level it's true for:
ALTER TABLESPACE pg_default SET (random_page_cost = 1.1);
CREATE ROLE reporting;
ALTER ROLE reporting SET work_mem = '64MB';
ALTER ROLE reporting SET plan_cache_mode = force_custom_plan;
SELECT spcname, spcoptions FROM pg_tablespace ORDER BY spcname;
SELECT r.rolname, s.setconfig
FROM pg_db_role_setting AS s JOIN pg_roles AS r ON r.oid = s.setrole
ORDER BY r.rolname;
ALTER TABLESPACE pg_default RESET (random_page_cost);
DROP ROLE reporting;| spcnamename | spcoptionstext[] |
|---|---|
| pg_default | {random_page_cost=1.1} |
| pg_global | null |
| rolnamename | setconfigtext[] |
|---|---|
| reporting | {work_mem=64MB,plan_cache_mode=force_custom_plan} |
(the last two lines put things back: a tablespace and a role belong to the whole server, not to one database.)
- postgresql.conf, ALTER SYSTEM: the defaults for everything
- ├── tablespaceALTER TABLESPACE ... SET (random_page_cost, seq_page_cost, effective_io_concurrency)
- └── ALTER DATABASE ... SET work_mem = ...
- ├── roleALTER ROLE reporting SET work_mem = '64MB'
- └── ALTER ROLE ... IN DATABASE ... SET
- ├── functionCREATE FUNCTION ... SET plan_cache_mode = force_custom_plan
- └── SET enable_nestloop = off
- └── transactionSET LOCAL ..., gone at COMMIT or ROLLBACK
SET LOCAL is the safest experiment: it ends with the transaction, so a forgotten switch can't leak into the rest of a pooled connection.
BEGIN;
SET LOCAL enable_hashjoin = off;
SHOW enable_hashjoin;
COMMIT;
SHOW enable_hashjoin;| enable_hashjointext |
|---|
| off |
| enable_hashjointext |
|---|
| on |
better inputs
most bad plans are bad estimates, and the estimates have their own controls (when estimates go wrong):
- a bigger sample for a skewed column:
ALTER TABLE … ALTER COLUMN … SET STATISTICS 1000(pg_stats and ANALYZE). - correlated columns:
CREATE STATISTICS(extended statistics). - a distinct count you know better than the sample can guess: override it, and ANALYZE keeps your number.
ALTER TABLE orders ALTER COLUMN customer_id SET (n_distinct = 500);
ANALYZE orders;
SELECT n_distinct FROM pg_stats WHERE tablename = 'orders' AND attname = 'customer_id';| n_distinctfloat4 |
|---|
| 500 |
- fresh statistics after bulk changes: ANALYZE, or tune autovacuum's analyze threshold for the table.
rewrites
the query's shape is yours too. rewrites that steer without lying to the planner:
- join order: with
join_collapse_limit = 1(per transaction, with SET LOCAL), explicit JOINs are joined in the order written (join order search). - a fence:
WITH … AS MATERIALIZEDorOFFSET 0computes a subquery on its own, so a misestimate inside it can't poison the join order outside (how subqueries get planned). - a predicate the statistics can see:
kind = 'view', notlower(kind) = 'view';created_at >= '2026-04-01', notdate(created_at) >= …. - keep an index out of it: an expression on the column, the oldest trick there is.
EXPLAIN SELECT * FROM customers WHERE id = 42;
EXPLAIN SELECT * FROM customers WHERE id + 0 = 42;the second can't use the primary key, and its estimate falls back to the 0.005 default (10 rows instead of 1). that's the cost of tricks: they work by hiding information, so they make estimates worse too. reach for them last, and leave a comment.
one level deeperpg_hint_plan
hints exist as an extension: pg_hint_plan reads comments like /*+ IndexScan(orders) HashJoin(c o) */ and forces scan methods, join methods and join order. it's widely used, and it's not part of postgres: you install it, and you own the hints when the data changes under them. the core answer is still: fix the estimate, then the costs, then the query.
keylines
- no hints in core postgres. you change the planner's inputs, not its decision.
- enable_* switches don't forbid: postgres 18 counts disabled nodes and prints Disabled: true when there's no other way.
- cost settings belong where they're true: server, tablespace, role. SET LOCAL for experiments.
- most fixes are estimate fixes: ANALYZE, statistics targets, CREATE STATISTICS, n_distinct overrides.
- rewrites (join_collapse_limit, fences, sargable predicates) steer the shape. tricks hide information.