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.
Code
-- 外层行数少 + 内层索引点查:嵌套循环 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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.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.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.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.
FAQ
- Name the tables involved in this file.
- The references are `orders`, `customers`, with 2 joins tying them together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.