Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

A report query joins 14 tables and its plan changes unpredictably between runs. Explain how PostgreSQL searches join orders and which settings affect it.

For a modest number of tables, PostgreSQL searches join orders exhaustively with dynamic programming. join_collapse_limit and from_collapse_limit, both 8 by default, cap how many items are flattened into one search, so beyond that an explicit JOIN order is partly kept as written. At geqo_threshold, 12 relations by default, the genetic query optimizer takes over, a randomized search that can land on very different plans when inputs change slightly, which is what a 14-table report hits. We can reduce or pre-aggregate the joins, control the order with join_collapse_limit = 1 and explicit JOINs, or adjust geqo_threshold and geqo_seed for that session, but good estimates on each join matter more than search breadth.

Why this question is asked

Reporting queries grow over time: every new column on the dashboard adds a join, and one day a query with 14 tables starts behaving erratically. To understand why, we need to know how the planner searches for a join order, because the number of possible orders explodes as tables are added and PostgreSQL switches strategies to cope. Interviewers ask this internals question to see whether we know those switches and the settings around them. In this answer, we will see why join order matters and how fast the search space grows, how the exhaustive search works, what the collapse limits do, how GEQO takes over at 12 relations, and what our options are.

1Why Join Order Matters and Grows So Fast

When a query joins several tables, the database joins two of them first, then joins the result with a third, and so on. The order matters enormously. Joining a 3,000 row region table with customers first and then with orders may process a few thousand intermediate rows, while joining orders with order_items first may produce hundreds of millions of rows before any filter applies.

The number of possible orders grows faster than exponentially. For 4 tables there are dozens of possible join trees; for 14 there are far too many to evaluate one by one, even ignoring that each join also has three possible methods. So the planner needs a strategy that does not try everything.

2The Exhaustive Search With Dynamic Programming

For a moderate number of tables, PostgreSQL uses dynamic programming. It first finds the cheapest way to scan each single table. Then it finds the cheapest way to produce every pair of tables that can be joined, keeping only the best plan for each pair (and for each useful sort order). Then every set of three, built from the best pairs, and so on, until it has the best plan for the full set.

This is exhaustive in the sense that it is guaranteed to find the cheapest plan according to its estimates, but it avoids recomputing shared parts. It still grows very quickly in time and memory as tables are added, which is why the next two mechanisms exist.

Step throughHow PostgreSQL picks a join search strategy
  1. Parse query, flatten JOINs and subqueriesup to join_collapse_limit / from_collapse_limit items, default 8
  2. Relations in one search at or above geqo_threshold (12)?
    YesGenetic optimizer: randomized searchNoDynamic programming: exhaustive search
  3. Best plan per relation setkept and combined into larger sets
  4. Final planonly as good as the row estimates at each join

4 steps in order. Play them, or step through them one at a time.

3The Collapse Limits

Before searching, the planner flattens the query: explicit JOIN clauses and subqueries in FROM are merged into one list of items whose order it is free to choose. join_collapse_limit, 8 by default, controls how many items from explicit JOIN syntax are merged into one list, and from_collapse_limit, also 8, does the same for subqueries in FROM. When a query has more items than the limit, the planner does not flatten past it; it plans parts separately and keeps the structure written in the query for the rest.

So in a 14-table query written with explicit JOINs, the planner does not consider all 14 tables in one free search. Part of the join order is effectively the order we wrote. Rearranging the JOIN clauses in the SQL text can therefore change the plan for large queries, which surprises people who expect the planner to treat SQL as purely declarative.

Java
SHOW join_collapse_limit; -- 8
SHOW from_collapse_limit; -- 8
SHOW geqo_threshold; -- 12
SHOW geqo; -- on

4GEQO: The Genetic Query Optimizer

When a single search would involve geqo_threshold relations or more, 12 by default, PostgreSQL switches to GEQO, the genetic query optimizer. Instead of evaluating every combination, it treats join orders like a population: it generates random orders, keeps the cheaper ones, combines and mutates them over several generations, and returns the best one it found. This is far faster for many tables but gives no guarantee of the best plan.

GEQO uses a random number generator seeded by geqo_seed, 0 by default, so for exactly the same query and the same statistics it is repeatable. But the search is sensitive: after an ANALYZE changes a few estimates, or when a slightly different query text changes the flattening, the random walk takes a different path and can land on a very different plan. For a 14-table report whose statistics change daily, that looks exactly like plans changing unpredictably between runs. Changing geqo_seed simply makes it explore a different random path.

5Options for the 14-Table Report

The most durable option is to reduce the number of relations in one search. Many report queries join lookup tables only to fetch a name; pre-aggregating the big fact tables in a CTE marked MATERIALIZED, a subquery, or a materialized view refreshed on a schedule leaves a much smaller join. If the report always reads the same aggregate, a materialized view is usually the best answer.

If we know the right order, we can tell PostgreSQL to keep it. Setting join_collapse_limit = 1 for the session or transaction makes the planner join tables in exactly the order of our explicit JOIN clauses, with no reordering, while it still chooses join methods. Alternatively, raising geqo_threshold above 14 for that session forces the exhaustive search, which costs more planning time, perhaps tens or hundreds of milliseconds for 14 tables, but is deterministic and finds the cheapest plan by estimates. For a report that runs for seconds, that planning time is often a good trade.

SQL
BEGIN;
SET LOCAL join_collapse_limit = 1; -- join exactly in the written order
-- or: SET LOCAL geqo_threshold = 20; -- force the exhaustive search for this report
SELECT ... FROM regions r
JOIN customers c ON c.region_id = r.id
JOIN orders o ON o.customer_id = c.id
...;
COMMIT;

SET LOCAL keeps the change inside this transaction, so other queries keep the defaults.

6Estimates Matter More Than Search Breadth

Even the perfect exhaustive search only finds the plan that is cheapest according to its estimates. In a 14-table join, estimation errors multiply: a 5x mistake at the third join and a 10x mistake at the sixth turn into a 50x error by the end, and the chosen order is built on numbers that are badly off. So before tuning the search, we check estimated against actual rows at each join in EXPLAIN ANALYZE and fix the worst gaps with ANALYZE, extended statistics on correlated filter columns, or rewritten predicates. A smaller query with good estimates beats a wider search over wrong ones.

7Follow-up questions

Does GEQO always produce a worse plan than the exhaustive search?

Not always, but it can, and there is no guarantee. For many queries it finds a plan close to the best, much faster than an exhaustive search would. The issue is stability rather than average quality: small changes in input can move it to quite different plans, which is painful for reports with strict timing.

Why not just raise join_collapse_limit and geqo_threshold globally?

Because planning time for the exhaustive search grows very quickly with the number of relations, and every query with many joins would pay it on every planning, including frequent ones from the application. Changing them per session or per report keeps the cost where we accept it.

Does writing the JOINs in a good order help without changing settings?

For queries with more items than join_collapse_limit, yes, because the planner partly keeps the written structure beyond that limit. Putting selective small tables first and grouping related joins can therefore help, but it is fragile; reducing the number of joins or fixing the order explicitly is clearer.

8Conclusion

In this answer, we saw that PostgreSQL finds join orders for a moderate number of tables with an exhaustive dynamic programming search, that join_collapse_limit and from_collapse_limit, 8 by default, cap how much of the query is flattened so explicit JOIN order is partly kept beyond that, and that from geqo_threshold, 12 by default, the randomized genetic optimizer takes over and can flip plans when inputs change. For the 14-table report we reduced the joins with pre-aggregation or materialized views, fixed the order with join_collapse_limit = 1, or forced the exhaustive search for that session, while remembering that accurate estimates at each join matter most.

What to say in the interviewAbout 100 seconds aloud

Open with

With 14 tables the number of possible join orders is enormous, so PostgreSQL changes strategy as queries grow. For a moderate number of relations it uses an exhaustive dynamic programming search: best plan for each table, then for each joinable pair, then each set of three, building up to the full set, which guarantees the cheapest plan by its estimates.

Then, if they want more

Two settings limit what goes into one search: join_collapse_limit and from_collapse_limit, both 8 by default, decide how many explicit JOIN items and FROM subqueries get flattened into one list. Beyond that, the planner keeps part of the structure we wrote, so the order of JOIN clauses starts to matter.

And once a search would cover geqo_threshold relations, 12 by default, it switches to the genetic query optimizer, which builds random join orders, keeps the cheaper ones and evolves them.

It is repeatable for identical input because of geqo_seed, but small changes in statistics or query text can send it to a very different plan, which matches what we see in this report.

My options would be to reduce the joins first, for example by pre-aggregating the big tables in a materialized view or CTE, or to control the order explicitly with join_collapse_limit set to 1 and careful JOIN syntax, or to raise geqo_threshold for that session so the exhaustive search runs, accepting more planning time.

But I would also check estimated against actual rows at each join, because errors multiply across 14 joins and good estimates matter more than a wider search.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A report query joins 14 tables and its plan changes unpredictably between runs. Explain...": https://scrivio-interview-library.netlify.app/databases/query-optimization/1a52d54830/