Nested Loop Versus Hash Join Plans

A few indexed rows make nested loop cheapest, while a full aggregate over both tables amortizes into one hash join build; EXPLAIN shows which wins.

SqlData Integrity

Code

snippet
-- 外层行数少 + 内层索引点查:嵌套循环 nested loop 每行一次索引查找即可
EXPLAIN
SELECT o.order_id, o.total_cents, c.email
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'pending'
LIMIT 20;

-- 全量聚合没有行数上限:哈希连接 hash join 一次构建哈希表、一次扫描探测
EXPLAIN
SELECT c.region, SUM(o.total_cents) AS revenue_cents
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.region;

-- 经验法则:预估行数决定连接方式,EXPLAIN 输出里的 rows 是判断依据

What the code does

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

In terms of clauses, the statements use: 2 JOINs combining rows across tables; a WHERE clause narrowing which rows one statement affects; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; a row cap (LIMIT) bounding the result size.

Caveats

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

Applying it

Run the statement against the orders table; the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

EXPLAIN
SELECT o.order_id, o.total_cents, c.email
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'pending'
LIMIT 20;
EXPLAIN
SELECT c.region, SUM(o.total_cents) AS revenue_cents
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.region;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
The references are `orders`, `customers`, with 2 joins tying them together.