Sub topic 6
Nested Loop, Hash and Merge Joins
Assume you can write SELECT queries with WHERE, JOIN, GROUP BY, and ORDER BY. You should also know that an index helps a database find rows without reading a whole table. This chapter uses PostgreSQL plan terminology.
A join node combines rows from two child nodes. PostgreSQL chooses a join method based on estimated row counts, available indexes, sort order, and cost. The plan usually labels the inputs as Outer and Inner. These names describe the join's execution roles, not necessarily SQL table order.
The three join methods
| Join method | Basic action | Often a good choice when |
|---|---|---|
| Nested Loop | For each outer row, find matching inner rows | The outer input is small and the inner input has a useful index |
| Hash Join | Build a hash table from one input, then probe it with the other | Inputs are large and the join uses equality |
| Merge Join | Read two sorted inputs together | Both inputs are already sorted or can be sorted cheaply |
The planner can choose a different method after data volume or statistics change. The SQL text alone does not determine the method.
Nested Loop
A nested loop takes one row from its outer input and searches the inner input for matches. If the inner side uses an index, this can be very efficient:
EXPLAIN
SELECT c.name, o.created_at
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE c.id = 42;A typical plan might contain:
Nested Loop
-> Index Scan using customers_pkey on customers c
-> Index Scan using orders_customer_id_idx on orders oThe first scan finds one customer. The second scan runs once for that customer. If the outer input contains 10,000 rows, however, the inner scan may run 10,000 times. That repeated work can make a nested loop slow.
A nested loop is not automatically bad. Look at the loops value in EXPLAIN ANALYZE. A cheap inner operation repeated a few times is often the right plan.
Hash joins
A hash join normally handles an equality condition such as o.customer_id = c.id. PostgreSQL reads one input and builds an in-memory hash table keyed by the join column. It then reads the other input and probes that table.
EXPLAIN
SELECT c.name, count(*)
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.name;A plan may contain:
Hash Join
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o
-> Hash
-> Seq Scan on customers cHash joins avoid one indexed lookup per outer row. They can be a good choice when both inputs are large. If the hash table does not fit in the allowed memory, PostgreSQL can divide it into batches and use temporary disk space. That increases I/O.
Merge joins
A merge join reads two inputs in join-key order. It advances the input whose current key is smaller and emits matching rows when the keys are equal. The inputs must already be sorted, or PostgreSQL must add Sort nodes.
Merge joins can work well for large inputs, especially when indexes provide the required order. They also support some non-equality join conditions that hash joins cannot use.
Choosing and checking a join
Do not change a join method just because its name looks expensive. Run the query with actual measurements:
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, o.created_at
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE c.id = 42;Compare estimated and actual rows at each join input. A large mismatch can cause PostgreSQL to choose a poor method. Refresh statistics with ANALYZE, add a suitable index, or rewrite a query only after identifying the cause.
Exercise
Why might PostgreSQL choose a nested loop for a query that joins a small customer result to a large orders table?
Show answer
The small outer result may make repeated indexed lookups into orders cheaper than scanning and hashing the whole orders table.