---
title: "SQL Physical Joins: Nested Loop / Hash Join"
description: "Scan every pair, then build and probe buckets. Same rows; different work."
source: https://vizlearn.app/cs/databases/sql-physical-joins
access: premium (interactive player requires Lifetime; this doc is free)
---

# SQL Physical Joins: Nested Loop / Hash Join

SQL physical joins determine how an engine finds the row pairs requested by a join. Nested Loop
checks every pair in its plain scan form. Hash Join first groups one input into hash buckets,
then checks candidates from the other input. Both must preserve every matching pair, including
those created by duplicate keys.

Which comparisons can you skip while keeping every matching pair? In this lesson, two four-row inputs produce
five output rows either way. Nested Loop performs sixteen pair tests. Hash Join performs seven
candidate tests, plus four build insertions and four probes. Those are different operations;
seven is not a runtime measurement.

## How Nested Loop and Hash Join Work

For an inner equijoin, a pair qualifies only when `l.key = r.key` is TRUE. A `NULL` key never
qualifies under this predicate, including against another `NULL`. Distinct rows with the same
key remain distinct records: two left rows and two right rows produce four row pairs.

**Nested Loop** picks one left row and scans the entire right input. It emits a pair whenever
the keys match, then continues scanning. At the next left row, the inner scan starts over.
There is no first-match exit: that would silently turn a join into a different computation.

**Hash Join** has two stages. Build scans the right input once, skips NULL keys, and appends
row references to buckets. Probe scans the left input, skips NULL keys, and visits the bucket
selected by each key. This model uses `key % bucket_count` so you can calculate every address.

A bucket contains candidates, not certified matches. Different keys can collide. The probe must
check the full key of every occupant before emitting a pair. Build stores a list of row
references, not one row per key, so repeated keys cannot overwrite one another. Probing does not
remove stored rows; another left row may need the same matches.

## Nested Loop and Hash Join Step by Step

Both executions use these inputs. IDs identify records; only `key` participates in the predicate.

| Left ID | Key | Right ID | Key |
| --- | --- | --- | --- |
| L1 | 1 | R1 | 1 |
| L2 | 2 | R2 | 1 |
| L3 | 1 | R3 | 5 |
| L4 | 4 | R4 | 2 |

1. **Scan for L1.** Nested Loop tests R1, R2, R3, R4. It emits `(L1, R1)` and `(L1, R2)`.
   Matching R1 does not finish the scan.
2. **Restart for L2.** The scan starts at R1 again, tests all four rows, and emits `(L2, R4)`.
3. **Finish the left input.** L3 repeats the key-1 matches, emitting `(L3, R1)` and `(L3, R2)`.
   L4 tests all four right rows and finds no match. Total: sixteen tests, five output rows.
4. **Build four buckets.** Hash Join stores R1, R2, R3 in bucket 1 because `1 % 4 = 5 % 4 = 1`.
   R4 goes into bucket 2. Buckets 0 and 3 stay empty. All four inserts finish before probing.
5. **Probe L1.** Bucket 1 supplies three candidates. R1 and R2 match; R3 fails because `1 != 5`.
   R4 is never tested for L1. For L2, bucket 2 supplies only R4, which matches.
6. **Probe L3 and L4.** L3 repeats the three bucket-1 tests and emits two more pairs. L4 visits
   empty bucket 0. Total: `3 + 1 + 3 + 0 = 7` candidate tests and the same five output pairs.

7. **Compare the search footprints.** The two matrices mark matches, checked unequal pairs, and
   untested pairs separately. Hash Join leaves nine pairs untested; the five matches stay identical.
8. **Collapse to one bucket.** The default ending keeps the rows fixed and rebuilds with `B = 1`.
   A grouped replay shows four tests per left row: sixteen tests, still five output pairs.

The first probe marks R1, R2, and R3 as candidates and R4 as skipped: equal keys must map to the
same bucket, so R4 cannot match L1. At the end, both matrices and work columns compare four-bucket
Hash with single-bucket Hash; the Nested Loop test count stays above as a reference.
Each output-pair cell records a receipt from each original plan, so you can
check equality of results separately from the work counters. These receipts do not deduplicate
records: a different row ID always denotes a different pair.

## Time and Space Complexity

Let `n` and `m` be input row counts, `B` the bucket count, `C` the number of candidate tests, and
`z` the number of output rows. The comparison concerns the algorithms shown, with nonempty
inputs where the product bound is used.

| Algorithm / condition | Time complexity | Auxiliary space, excluding output |
| --- | --- | --- |
| Plain Nested Loop | O(nm + z), regardless of how many pairs match | O(1) |
| Hash Join, exact work model | O(B + n + m + C + z) | O(B + m) |
| Hash Join, B = Θ(m) with well-distributed hashes | Expected O(n + m + z) | O(B + m) |
| Hash Join, all rows in one bucket | O(B + n + m + nm) | O(B + m) |

Both displayed functions collect results, requiring another O(z) space. If every key is equal,
`z = nm`: hashing cannot avoid writing the answer. If no keys match and buckets separate the
inputs, candidate tests can be zero, but building and probing still require work.

The default ending includes the one-bucket contrast. Choose **One bucket** to replay it in full. Hash Join now makes sixteen
candidate tests too, with build and probe overhead still present. The animation does not assign
those operations equal runtime costs or claim which plan a real optimizer will choose.

## Edge Cases

- **Repeated keys:** four equal rows per side produce sixteen output pairs, not four.
- **Hash collision:** keys 1 and 5 share bucket 1 with four buckets but do not match each other.
- **NULL keys:** Nested Loop rejects their pairs; Hash Join skips them during build and probe.
- **No overlap:** an inner join returns no rows. It does not add NULL-padded rows.
- **Empty input:** the result is empty. In the shown implementation, an empty probe input still
  allows the build loop to run; an empty build input still receives non-NULL probes.

## Common Mistakes

- Omitting the full-key test after hashing creates false matches from collisions.
- Keeping one row per key or stopping after one match loses valid duplicate-key pairs.
- Deleting a bucket after a successful probe prevents later left rows from reusing its matches.
- Calling the expected hash bound O(n + m) hides the output term and its assumptions.
- Treating this traversal order as a SQL guarantee forgets that ordering requires `ORDER BY`.

## A Note on Simplification

This is an in-memory inner equijoin with a plain tuple-at-a-time Nested Loop and a small,
separately chained hash table. The four-row input limit is a visualization limit. Right is fixed
as the build input; the lesson does not automatically choose the smaller side.

Real engines may use indexed or block Nested Loop, larger hash functions, spilling and batching,
parallel or vectorized execution, and estimates based on row counts and widths. An index can
make Nested Loop attractive; a build input that does not fit memory changes Hash Join's costs.
Those choices are outside the displayed counters. PostgreSQL describes these execution choices
in [Planner/Optimizer](https://www.postgresql.org/docs/18/planner-optimizer.html) and distinguishes
plan costs from observed execution in [Using EXPLAIN](https://www.postgresql.org/docs/18/using-explain.html).
