Join Collapse Limit Pins Explicit Order

Set join_collapse_limit to 1 and the planner stops reordering explicit JOINs, so the written sequence becomes the join sequence whenever you know a better one.

SqlData Fetching

Code

snippet
CREATE TABLE a (i int PRIMARY KEY);
CREATE TABLE b (i int PRIMARY KEY);
CREATE TABLE c (i int PRIMARY KEY);
CREATE TABLE d (i int PRIMARY KEY);
INSERT INTO a SELECT g FROM generate_series(1, 1000) g;
INSERT INTO b SELECT g FROM generate_series(1, 1000) g;
INSERT INTO c SELECT g FROM generate_series(1, 1000) g;
INSERT INTO d SELECT g FROM generate_series(1, 1000) g;

-- 默认值与 from_collapse_limit 相同:planner 自由重排四个表的连接顺序
EXPLAIN (COSTS OFF)
SELECT count(*)
FROM a JOIN b ON b.i = a.i
       JOIN c ON c.i = b.i
       JOIN d ON d.i = c.i;

-- 设为 1:显式 JOIN 结构不再被重排,书写顺序即连接顺序
SET join_collapse_limit = 1;
EXPLAIN (COSTS OFF)
SELECT count(*)
FROM a JOIN b ON b.i = a.i
       JOIN c ON c.i = b.i
       JOIN d ON d.i = c.i;
RESET join_collapse_limit;

Inside the snippet

What runs here is SELECT / INSERT / CREATE / EXPLAIN — a, generate_series, b, c and d are the objects involved.

Breaking the statements into their working parts: 6 JOINs combining rows across tables; COUNT aggregation; a PRIMARY KEY that enforces row identity.

Watch out for

  • Row counts compound across 6 joins; make sure the join keys are indexed before adapting this to production data volumes.

Using it

The a table is the working surface here.

Key statements

EXPLAIN (COSTS OFF)
SELECT count(*)
FROM a JOIN b ON b.i = a.i
       JOIN c ON c.i = b.i
       JOIN d ON d.i = c.i;
INSERT INTO a SELECT g FROM generate_series(1, 1000) g;
INSERT INTO b SELECT g FROM generate_series(1, 1000) g;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`a`, `generate_series`, `b`, `c`, `d` — joined via 6 JOIN clauses.