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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `a`, `generate_series`, `b`, `c`, `d` — joined via 6 JOIN clauses.
Report a problem with this exampleOpens a pre-filled issue on GitHub.