Merge Join Plan Ordering

Feed a Merge Join with pre-sorted inputs: when both sides have matching index order the planner merges streams in one pass without a hash table.

SqlData Fetching

Code

snippet
-- Merge Join 需要两侧按连接键有序:索引顺序直接满足
CREATE TABLE customers (id int PRIMARY KEY, name text);
CREATE TABLE orders (
    id          int PRIMARY KEY,
    customer_id int NOT NULL REFERENCES customers(id),
    amount      numeric NOT NULL
);
CREATE INDEX idx_orders_customer ON orders (customer_id);

-- 等值连接两侧各有序:planner 可选 Merge Join(一次性合并,无哈希表)
EXPLAIN (COSTS OFF)
SELECT c.name, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id;

-- 让其中一侧无序可用(大表 + 关闭索引),观察 planner 退回
-- Hash Join 或先加 Sort 节点再 Merge Join 的取舍
SET enable_indexscan = off;

EXPLAIN (COSTS OFF)
SELECT c.name, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id;

RESET enable_indexscan;
DROP TABLE orders, customers;

What the code does

Several statements share this file — SELECT / CREATE / EXPLAIN, with customers and orders among the objects involved.

Mechanically, the statements are built from: 2 JOINs combining rows across tables; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard tying rows to the parent table.

What to watch for

  • 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.

Applying it

The customers table is the working surface here.

Statements that matter

EXPLAIN (COSTS OFF)
SELECT c.name, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id;
CREATE TABLE orders (
id          int PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers(id),
amount      numeric NOT NULL
);
CREATE INDEX idx_orders_customer ON orders (customer_id);

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`customers`, `orders`, combined through 2 joins.