Sub topic 2
Nested loop, hash and merge joins
This chapter assumes you can write SELECT queries with JOIN, GROUP BY and ORDER BY, know what an index is, and can run EXPLAIN in psql. The examples use PostgreSQL.
Join node types
A join node shows how the planner matches rows from two inputs. PostgreSQL uses one of three strategies:
- Nested loop: For each row from the outer input, the database looks up matching rows in the inner input. It works well when the outer input is small and the inner side has an index.
- Hash join: The database builds a hash table from one input, then probes it with each row of the other. It suits large, unsorted inputs joined on equality.
- Merge join: Both inputs are sorted on the join key, then read together in step. It suits inputs that are already sorted or have indexes in key order.
EXPLAIN
SELECT c.name, o.id
FROM customers c
JOIN orders o ON o.customer_id = c.id;Sorts, aggregates and limits
A Sort node orders rows for ORDER BY or for a merge join. Look for "external merge" in its output. That means the sort spilled to disk. HashAggregate and GroupAggregate nodes compute GROUP BY. GroupAggregate needs sorted input, so it often sits above a Sort. A Limit node returns only the requested rows, but a Limit above a Sort still sorts every row first.
EXPLAIN ANALYZE: actual time and actual rows
Plain EXPLAIN shows estimates only. EXPLAIN ANALYZE runs the query and adds actual time and actual row counts to each node. Compare the estimated rows with the actual rows value. A large gap usually means the planner's statistics are stale. Run ANALYZE on the table to refresh them. Also check loops: the actual row count is per loop, so a node inside a nested loop may run many times.
Using EXPLAIN ANALYZE on INSERT, UPDATE and DELETE safely
EXPLAIN ANALYZE really executes the statement. Wrap a data-changing statement in a transaction and roll it back:
BEGIN;
EXPLAIN (ANALYZE)
UPDATE orders
SET status = 'archived'
WHERE created_at < DATE '2020-01-01';
ROLLBACK;Exercise
A query joins a 10-row table to a 5-million-row table on an indexed key. Which join node do you expect, and why?
Show answer
A nested loop. Each of the 10 outer rows triggers one fast index lookup on the large table.