skip to content

join order search

n tables, n! orders. dynamic programming, join_collapse_limit, and the genetic optimizer past 12 tables.

address
everything.optimizer.join_ordering
part
part 10, the optimizer
chapter
chapter 6 of 10
reading time
8 min

a join of n tables can be done in a huge number of orders: n! just for the left-deep ones. postgres finds the cheapest with dynamic programming: cheapest way to join every pair, then every set of three built from those, up to all n. that's exhaustive and exact, and it grows like 2ⁿ.

two settings keep it in check. join_collapse_limit and from_collapse_limit (8) stop the planner from reordering more than 8 items at once, and past geqo_threshold (12) items it switches to a genetic search that's fast and usually close.

the picture

you know how the order you write JOINs in doesn't matter, except sometimes it does? the planner is free to reorder them, up to a point, and past that point it stops.

think of planning a road trip through four cities. you could try every order and price each, and with four that's 24 tours. with 12 it's 479 million. the smart way is to note the cheapest route between every pair of cities once, then build the cheapest three-city routes out of those, and so on. you never price a bad route twice. that's what postgres does with tables.

here's one query, written in a bad order (products first), with the planner free to reorder and with it told not to:

join_collapse_limit =
FROM =
query.sql
  1. 1SET join_collapse_limit = 8;
  2. 2
  3. 3SELECT p.name, oi.qty
  4. 4FROM products AS p
  5. 5JOIN order_items AS oi ON oi.product_id = p.id
  6. 6JOIN orders AS o ON o.id = oi.order_id
  7. 7JOIN customers AS c ON c.id = o.customer_id
  8. 8WHERE c.id = 42
  9. 9ORDER BY p.name, oi.qty;
the result for 8 | JOIN
nametextqtyint4
bamboo cookbook1
cast iron pan4
cat tree1
chef's knife1
chef's knife2
classic cutting board1
… 12 more
(18 rows)
the plan

join_collapse_limit 8, the default: the planner flattens the four JOINs and searches every order. it starts from customer 42.

real output, postgres 18.6 (PGlite 0.5.12) · join-order
switch join_collapse_limit between 8 (the default) and 1, and the FROM between explicit JOINs and a comma list. with 1 and JOINs, the planner joins in the order written: all of products with all 24,942 order items first. the commas aren't affected by join_collapse_limit at all. toggle cost to see each node's share.

273.90 for the free plan, 763.00 for the written order: the planner's best guess at how much worse it is. same result either way.

n tables, n! orders

how many ways to join n tables? counting only left-deep trees (each join adds one table to what's built so far), it's n!: every order of the tables. bushy trees (two joins joined to each other) add more. postgres's dynamic programming instead works over sets of tables, and there are only 2ⁿ − 1 of them:

4 tables: orders24
4 tables: sets15
6 tables: orders720
6 tables: sets63
8 tables: orders40,320
8 tables: sets255
10 tables: orders3,628,800
10 tables: sets1,023
12 tables: orders479,001,600
12 tables: sets4,095
14 tables: orders87,178,291,200
14 tables: sets16,383
log scale
real output, postgres 18.6 (PGlite 0.5.12) · join-order
left-deep join orders (n!) against the sets of tables dynamic programming prices (2ⁿ − 1), on a log scale. at 12 tables, the default geqo_threshold, it's 479 million orders against 4,095 sets. the sets still grow exponentially, and each set can be split many ways, which is why there's a threshold at all.
sqlempty db
SELECT n, factorial(n) AS orders, (2 ^ n)::bigint - 1 AS subsets
FROM generate_series(2, 14) AS n
ORDER BY n;
output, from postgres 18.6
SELECT 13
nint4ordersnumericsubsetsint8
223
367
42415
512031
672063
75040127
840320255
9362880511
1036288001023
11399168002047
124790016004095
1362270208008191
148717829120016383
(13 rows)

dynamic programming, level by level

for the shop query, the four tables are linked in a chain: customers → orders → order_items → products. the planner builds up:

  • ├── customersindex scan, id = 42: 1 row
  • ├── ordersseq scan, 10,000 rows
  • ├── order_itemsseq scan, or its primary key per order
  • └── productsseq scan, 200 rows

level 1: one table each. the cheapest scans of each, priced with the cost model: an index scan of customers for id = 42, a seq scan of orders, and so on.

level 1/4
drawn by hand · the textbook dynamic programming search, as postgres's join search does it
the planner's search for four tables, drawn by hand: the sets it prices at each level. it only joins sets that share a join condition, so customers and products never meet on their own (that would be a cross join). at every level it keeps the cheapest paths for each set, the way the cost model keeps the cheapest scan.

the important bit: a set's cheapest path is computed once and reused by every bigger set that contains it. that's what turns n! into something closer to 2ⁿ. it's also why the planner considers plans that start from customer 42 even though you wrote products first.

the limits

sqlempty db
SELECT name, setting FROM pg_settings
WHERE name IN ('join_collapse_limit', 'from_collapse_limit', 'geqo', 'geqo_threshold')
ORDER BY name;
output, from postgres 18.6
SELECT 4
nametextsettingtext
from_collapse_limit8
geqoon
geqo_threshold12
join_collapse_limit8
(4 rows)
  • join_collapse_limit (8): explicit JOINs are flattened into one list to reorder only while the list stays at 8 items or fewer. past that, the joins are planned in groups, in the order written. at 1, every explicit JOIN is planned where you wrote it, which is how you'd force an order without hints (steering the planner).
  • from_collapse_limit (8): the same for subqueries in FROM being pulled up into their parent's list, and for comma-separated FROM lists.
  • geqo_threshold (12): when a list to reorder has 12 or more items, dynamic programming is replaced by the genetic query optimizer.

OUTER JOINs are reordered only where that's provably the same result (outer joins has why), so a chain of LEFT JOINs often stays close to the written order anyway.

predict the output
join_collapse_limit = 1. which FROM still gets reordered?
sql
SET join_collapse_limit = 1;

the genetic optimizer

past 12 tables, postgres treats join orders like a population: random orders, scored by cost, the cheaper ones recombined for a number of generations. it's a heuristic: fast, and not guaranteed to find the best plan. it's deterministic for a given geqo_seed (0 by default), so the same query gets the same plan.

here's a chain of 10 to 14 small tables, joined with join_collapse_limit raised so nothing gets split, planned with the genetic optimizer and with the exhaustive search:

sqlempty db · session geqo
DO $$
BEGIN
  FOR i IN 1..14 LOOP
    EXECUTE format('CREATE TABLE t%s (id int PRIMARY KEY, next_id int, v int)', i);
    EXECUTE format('INSERT INTO t%s SELECT g, (g * 7) %% %s + 1, g %% (%s + 2) FROM generate_series(1, %s) AS g ORDER BY g', i, 100 * (15 - i), i, 100 * i);
    EXECUTE format('ANALYZE t%s', i);
  END LOOP;
END $$;
CREATE FUNCTION chain(n int) RETURNS text LANGUAGE sql AS $$
  SELECT 'SELECT count(*) FROM t1' || string_agg(format(' JOIN t%s ON t%s.id = t%s.next_id AND t%s.v < %s', i, i, i - 1, i, i % 4 + 1), '' ORDER BY i)
  FROM generate_series(2, n) AS i
$$;
CREATE FUNCTION plan_cost(q text) RETURNS numeric LANGUAGE plpgsql AS $$
DECLARE j json;
BEGIN
  EXECUTE 'EXPLAIN (FORMAT JSON) ' || q INTO j;
  RETURN (j->0->'Plan'->>'Total Cost')::numeric;
END $$;
SET join_collapse_limit = 20;
SELECT n, plan_cost(chain(n)) AS cost FROM generate_series(10, 14) AS n ORDER BY n;
SET geqo = off;
SELECT n, plan_cost(chain(n)) AS cost FROM generate_series(10, 14) AS n ORDER BY n;
output, from postgres 18.6
#1 · DO
#2 · CREATE FUNCTION
#3 · CREATE FUNCTION
#4 · SET
#5 · SELECT 5
nint4costnumeric
1034.68
1135.16
1239.76
1344.68
1480.00
(5 rows)
#6 · SET
#7 · SELECT 5
nint4costnumeric
1034.68
1135.16
1235.61
1336.58
1437.20
(5 rows)
10 tables: geqo34.68
10 tables: exhaustive34.68
11 tables: geqo35.16
11 tables: exhaustive35.16
12 tables: geqo39.76
12 tables: exhaustive35.61
13 tables: geqo44.68
13 tables: exhaustive36.58
14 tables: geqo80
14 tables: exhaustive37.2
real output, postgres 18.6 (PGlite 0.5.12) · join-order
the cheapest plan each search found for a chain of n tables, in cost units. below 12 the genetic optimizer isn't used and the two are identical. from 12 on, it settles for worse plans: at 14 tables, more than twice the cost of the best one.

worse plans in exchange for planning time: the exhaustive search over 14 tables can take long enough to matter on every execution. if a big join gets a bad plan, raising geqo_threshold (and the collapse limits) can help, and so can splitting the query so the planner sees smaller problems. measure planning time with EXPLAIN (ANALYZE, SUMMARY ON) when you try.

keylines

  • n tables have n! left-deep join orders. postgres doesn't try them all.
  • dynamic programming prices sets of tables level by level and reuses each set's cheapest path.
  • explicit JOINs are reordered within join_collapse_limit (8), FROM lists within from_collapse_limit (8).
  • at geqo_threshold (12) items, a genetic search takes over: faster, not always the best plan.
  • join_collapse_limit = 1 follows the written JOIN order.