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:
- 1SET join_collapse_limit = 8;
- 2
- 3SELECT p.name, oi.qty
- 4FROM products AS p
- 5JOIN order_items AS oi ON oi.product_id = p.id
- 6JOIN orders AS o ON o.id = oi.order_id
- 7JOIN customers AS c ON c.id = o.customer_id
- 8WHERE c.id = 42
- 9ORDER BY p.name, oi.qty;
| nametext | qtyint4 |
|---|---|
| bamboo cookbook | 1 |
| cast iron pan | 4 |
| cat tree | 1 |
| chef's knife | 1 |
| chef's knife | 2 |
| classic cutting board | 1 |
| … 12 more | |
join_collapse_limit 8, the default: the planner flattens the four JOINs and searches every order. it starts from customer 42.
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:
SELECT n, factorial(n) AS orders, (2 ^ n)::bigint - 1 AS subsets
FROM generate_series(2, 14) AS n
ORDER BY n;| nint4 | ordersnumeric | subsetsint8 |
|---|---|---|
| 2 | 2 | 3 |
| 3 | 6 | 7 |
| 4 | 24 | 15 |
| 5 | 120 | 31 |
| 6 | 720 | 63 |
| 7 | 5040 | 127 |
| 8 | 40320 | 255 |
| 9 | 362880 | 511 |
| 10 | 3628800 | 1023 |
| 11 | 39916800 | 2047 |
| 12 | 479001600 | 4095 |
| 13 | 6227020800 | 8191 |
| 14 | 87178291200 | 16383 |
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:
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
SELECT name, setting FROM pg_settings
WHERE name IN ('join_collapse_limit', 'from_collapse_limit', 'geqo', 'geqo_threshold')
ORDER BY name;| nametext | settingtext |
|---|---|
| from_collapse_limit | 8 |
| geqo | on |
| geqo_threshold | 12 |
| join_collapse_limit | 8 |
- 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.
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:
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;| nint4 | costnumeric |
|---|---|
| 10 | 34.68 |
| 11 | 35.16 |
| 12 | 39.76 |
| 13 | 44.68 |
| 14 | 80.00 |
| nint4 | costnumeric |
|---|---|
| 10 | 34.68 |
| 11 | 35.16 |
| 12 | 35.61 |
| 13 | 36.58 |
| 14 | 37.20 |
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.