Join Methods (NL, Hash, Sort Merge)
A join method is the order and data structure used to find the row pairs that satisfy the join condition in two row sets. There are three methods. The NL join (Nested Loops) looks up the inner side for each outer row. The hash join loads one side into memory as a hash table and probes it with the other side. The sort merge join orders both sides by the join key and reads them side by side. Every method returns the same result rows; only the amount read and the memory used differ. The optimizer chooses the method together with the join order, and each product provides hints or settings that change that choice.
Key Specs
| NL join | Hash join | Sort merge join | |
|---|---|---|---|
| How it works | Looks up the inner side once per outer row | Builds a hash table from the smaller side (Build) and probes it for each row of the larger side (Probe) | Sorts both sides by the join key, then reads them side by side from the start |
| Main cost | Outer row count × cost of one inner lookup | Reading each side once + memory for the Build side | Sort (skipped if already sorted) + reading each side once |
| What it needs | An index on the inner join key (otherwise it reads the whole inner side every time) | Work memory big enough for the Build side | Sort memory, or an index in join key order |
| Join condition | Any condition (equality, range, LIKE, function) | Equality only | Equality. Oracle also handles ranges (<, BETWEEN) |
| When the first row appears | Immediately | After Build finishes | After both sorts finish |
| When it wins | Few outer rows and the inner side is found by index, Top-N | Both sides are large and an inner index is no help, aggregation batches | Both sides are already in join key order, range joins, memory is short |
| If memory runs short | Not applicable | Splits the Build side and spills it to temporary files (read multiple times) | Spills the sort to temporary files |
| PostgreSQL | MySQL (InnoDB) | Oracle | SQL Server | KDBS | |
|---|---|---|---|---|---|
| NL join | Nested Loop | Default method (ref, eq_ref in EXPLAIN) | NESTED LOOPS | Nested Loops | Lookup, Probe, IndexProbe in the step chain |
| Hash join | Hash Join | Inner hash join since 8.0.18 | HASH JOIN | Hash Match | An in-statement memory map when the inner side has neither an index nor a Cabin. A join in the query layer |
| Sort merge join | Merge Join | None | MERGE JOIN + SORT JOIN | Merge Join | None |
| NL inner cache | Memoize (since 14) | None | Scalar subquery cache (not a join) | None (Table Spool holds the inner side) | memo_hits |
| Method switch during execution | None | None | Adaptive plan (since 12c) | Adaptive Join (since 2017, batch mode) | None |
| Ways to set the method | enable_nestloop, enable_hashjoin, enable_mergejoin | Hints BNL and NO_BNL (turn hash join on and off), optimizer_switch | Hints USE_NL, USE_HASH, USE_MERGE | Join hints such as OPTION (LOOP JOIN) and INNER HASH JOIN | None. ACCESS and BUILD in CREATE PLAN |
| Hash and sort memory | work_mem × hash_mem_multiplier (4MB × 2) | join_buffer_size (256KB) | PGA work area (PGA_AGGREGATE_TARGET) | Query memory grant | join_build_max_rows (65,536 rows) |
NL Join
An NL join is a double loop. It reads one row from the outer (driving) set, looks up the inner table with that row's join key, and moves on to the next outer row. The inner lookup repeats once per outer row, so the cost is outer row count × cost of one inner pass.
- The inner index is everything. If the inner join key has an index, one lookup takes a few blocks; if not, every outer row reads the entire inner table. With 10,000 outer rows and 1 million inner rows, it compares 10 billion rows.
- The outer side must be small. The more the conditions narrow the outer side first, the fewer the iterations. So NL join performance depends heavily on the join order (which table is outer) (Driving Set and Join Order).
- The first row appears immediately. Once it finds the match for the first outer row, it can return it, which suits Top-N statements that fetch a few rows with
LIMITorFETCH FIRST. If the outer side is read through an index in the desired sort order, the sort is also skipped (Top-N Join). - It does not restrict the condition. It works even when the condition for finding the inner side is not equality (range,
LIKE, function). It is the method left when the other two cannot be used.
There are also devices that reduce the waste of looking up the same inner key many times. Memoize, available from PostgreSQL 14, caches the inner result by key and does not read the inner side when the same key comes again (Memoize). Oracle's NL batching (since 11g) collects ROWIDs found in the inner index and reads the table blocks all at once, and the execution plan shows NESTED LOOPS twice, stacked. SQL Server adds WITH UNORDERED PREFETCH, which requests inner reads ahead of time. MySQL's BKA (Batched Key Access) has the same purpose but is off by default (batched_key_access=off in optimizer_switch).
Hash Join
A hash join has two phases. In the Build phase, it reads all of the smaller input and builds a hash table on the join key. In the Probe phase, it reads the larger input once and probes the hash table for each row. Each side is read only once, so no inner index is needed, and when joining large sets the repeated lookups of an NL join disappear.
Figure. The two phases of a hash join and what happens when memory runs short
flowchart LR
subgraph B["① Build"]
C["Smaller input<br/>customers 100K rows"] --> H["Hash table<br/>key: cust_id"]
end
subgraph P["② Probe"]
O["Larger input<br/>orders 2M rows"] -->|"probe by hash per row"| H
H --> R["Matching row pairs"]
end
H -.->|"if work memory is exceeded"| S["Split the input into batches,<br/>write them to temporary files,<br/>and re-read each batch"]
Diagram explanation: Execution order runs from left to right.
① Buildreads the smaller input to the end and builds theHash table. No result row appears before this phase finishes.② Probereads the larger input once and, for each row, looks up the hash table with the hash value of the join key. The larger side is not loaded into memory.- The dotted line is the case where the hash table exceeds work memory. The input is split into several batches by hash value and written to temporary files, and each batch is re-read and joined. The result is the same, but disk I/O increases.
- Only equality conditions work. A hash puts only equal values in the same slot, so there must be at least one condition of the form
a.x = b.x. A range join (BETWEEN) cannot use a hash join (Range Join). - The smaller side must be Build. The side loaded into memory is the side that is smaller in bytes, not in row count. The optimizer chooses by estimate, and if the estimate is wrong, the larger side becomes Build and exceeds memory. Even in an outer join, the preserved table does not have to be Build (
HASH JOIN RIGHT OUTER, Direction of an Outer Join). - Memory is allocated per operation. PostgreSQL's
work_memand MySQL'sjoin_buffer_sizeare limits for one hash or sort operation, not for one connection. A statement with three hash joins uses three times as much, and parallel workers use that much more per worker. Raising it globally multiplies it by the number of concurrent executions, so raise it only in large batch sessions (PostgreSQL memory, MySQL memory).
Sort Merge Join
A sort merge join sorts both sides in join key order, then moves two cursors side by side from the start of the two lists. When the keys are equal, it emits the pair, and it advances the cursor on the smaller side. Once sorting is done, it reads each side only once.
- Sorting is most of the cost. If both sides are already in join key order (the join key index is read in order, or the previous step emits them sorted that way), the sort disappears and it becomes the cheapest method. In the PostgreSQL measurement below, a
Merge Jointhat read both sides through indexes was faster than aHash Join. - Range joins. Oracle uses a sort merge join even for non-equality conditions such as
a.x BETWEEN b.lo AND b.hi. Thanks to the sorted order, it only has to look from the start of the interval, so it does not re-read the entire inner side once per interval as an NL join does. The merge joins of PostgreSQL and SQL Server require an equality condition. - It degrades more gently when memory is short. A sort reads and writes sequentially even when it spills to temporary files, so performance drops more gradually than when a hash join splits into many batches.
- MySQL and KDBS do not have it. MySQL uses only NL and hash joins, and KDBS uses only NL-family steps and the memory map.
How the Optimizer Chooses
The optimizer computes the cost of each method from estimated row counts and chooses the cheapest. So the most common cause of a wrong join method is not the method itself but the row count estimate.
| Direction of the wrong estimate | Method chosen | What actually happens |
|---|---|---|
| Outer row count underestimated | NL join | Inner lookups repeat thousands of times more than expected |
| Outer row count overestimated | Hash join | Reads the entire larger side for something that would finish in a few rows |
| Build side size underestimated | Hash join | Exceeds work memory and spills to temporary files |
To reduce this risk, Oracle and SQL Server change the method during execution.
- Oracle adaptive plan. It builds a plan that holds both an NL join and a hash join and places a
STATISTICS COLLECTORabove the outer input. If the actual row count exceeds the threshold, it runs the hash join. Lines that were not used are marked with-in the+ADAPTIVEformat ofDBMS_XPLAN(optimizer_adaptive_plans, defaultTRUE). - SQL Server Adaptive Join. In batch mode execution, after the
Adaptive Joinoperator has read all of the Build input, it proceeds as an NL join if the row count is below the threshold (Adaptive Threshold Rows) and as a hash join if it is above. In 2017 a columnstore index is required, and from 2019 rowstore tables can also run in batch mode at compatibility level 150 or higher (Enterprise and Developer editions).
The ways to pin the method directly also differ by product. PostgreSQL has no hints, so it blocks a method with planner settings such as enable_hashjoin = off. Changing such settings globally narrows the choices for every statement (NL Join vs Hash Join). Oracle uses LEADING, USE_NL, USE_HASH, USE_MERGE, and SWAP_JOIN_INPUTS, which changes the Build side. A SQL Server join hint such as INNER HASH JOIN also fixes the join order as written, along with the method, so use OPTION (HASH JOIN) to change only the method. KDBS has no hints in SQL, and the administrator decides with ACCESS and BUILD in CREATE PLAN (Join Order and Plans).
Product Characteristics
- PostgreSQL. It uses all three methods. A hash table uses up to
work_mem × hash_mem_multiplier(default 4MB × 2 = 8MB), and beyond thatBatchesbecomes greater than 1. Since 11, it usesParallel Hash, where parallel workers build one hash table together. If the NL inner side repeats with the same keys,Memoizeis attached from 14. - MySQL. For a long time it had only NL joins, and for an inner side without an index it used block NL (BNL), which gathers outer rows up to
join_buffer_sizeand reads the inner side once per block. Hash join arrived in 8.0.18, and from 8.0.20 hash join replaces BNL. Check whether a hash join is used withInner hash joininEXPLAIN FORMAT=TREE. After 8.0.19, theHASH_JOINandNO_HASH_JOINhints have no effect, and theBNLandNO_BNLhints turn hash join on and off. There is no sort merge join. - Oracle. It has the three methods plus
MERGE JOIN CARTESIAN, which has no join condition. The memory of a hash join is set by the automatic PGA work area, and the number in parentheses afterUsed-MeminMEMSTATSis the number of times it went through temporary files (0 means it finished in memory) (Oracle memory). A sort merge join appears in the execution plan asSORT JOINunderMERGE JOIN, and it also handles range joins. - SQL Server. It uses all three methods. The hash join operator is named
Hash Match, and the same name is used for aggregation. Hash and sort memory is granted all at once before execution as a query memory grant, and if it falls short, SQL Server spills totempdband the execution plan gets a Hash Warning or Sort Warning (SQL Server memory). Merge-joining two sides with duplicate keys becomes a many-to-many merge that uses a work table. - KDBS. It does not choose the method by cost. An inner equality join is compiled into a step chain, and the inner access is decided by the catalog. If the inner join key is the tuple key it uses
Probe, and if it is an index it usesIndexProbe; both are NL joins. If the inner side has neither an index nor a Cabin, it builds a memory map once inside the statement (join_build_max_rows, 65,536 rows by default). Joins that the step chain does not handle, such as outer joins, are joined by the query layer, which hashes on the equality inON. The only thing the engine decides from statistics is the join order (Join Order and Plans).
In the Sandbox
In this site's sandbox, customers (100K rows) and orders (2M rows) were joined on cust_id and measured (PostgreSQL 17.12, Oracle 23.26, SQL Server 2022 CU28, KDBS v3.4.17. MySQL has no sandbox).
PostgreSQL: with parallel execution off (max_parallel_workers_per_gather = 0), the same statement was forced to each method.
SELECT count(*) FROM customers c JOIN orders o ON o.cust_id = c.cust_id;
| Forced method | Execution plan | Execution time |
|---|---|---|
| Default (hash) | Hash Join, Build customers: Buckets: 131072 Batches: 1 Memory Usage: 4540kB | 195 ms |
Hash, work_mem = 256kB | Buckets: 16384 Batches: 16 Memory Usage: 359kB | 258 ms |
Merge (enable_hashjoin and enable_nestloop off) | Merge Join, Index Only Scan on both sides (customers_pk, orders_x1), no sort | 169 ms |
NL (enable_hashjoin and enable_mergejoin off) | Nested Loop → Memoize (Hits: 1602242 Misses: 397758) → Index Only Scan | 598 ms |
- With the default
work_mem(4MB) ×hash_mem_multiplier(2), the 4.5MB hash table fit in one batch. Whenwork_memwas cut to 256kB, it split into 16 batches and became 32% slower. - Both sides had indexes in join key order, so the merge join finished without a sort and was the fastest in this single-run measurement. The optimizer's default choice was the hash join.
- The NL join looked up a customer for each of the 2M
ordersrows, andMemoizeanswered 1.6 million of them from the cache. It was still the slowest.
Oracle: the statement joining only 50 customers ran as an NL join (with NL batching, NESTED LOOPS twice), and the aggregation by region ran as a hash join in an adaptive plan.
| Id | Operation | Name | Starts | E-Rows | A-Rows |
| 1 | HASH GROUP BY | | 1 | 5 | 5 |
| * 2 | HASH JOIN | | 1 | 1983K | 2000K |
|- 3 | NESTED LOOPS | | 1 | 1983K | 100K |
|- 4 | NESTED LOOPS | | 1 | | 100K |
|- 5 | STATISTICS COLLECTOR | | 1 | | 100K |
| 6 | TABLE ACCESS FULL | CUSTOMERS | 1 | 100K | 100K |
|- * 7 | INDEX RANGE SCAN | ORDERS_X1 | 0 | | 0 |
|- 8 | TABLE ACCESS BY INDEX ROWID| ORDERS | 0 | 20 | 0 |
| 9 | TABLE ACCESS FULL | ORDERS | 1 | 2000K | 2000K |
- this is an adaptive plan (rows marked '-' are inactive)
After STATISTICS COLLECTOR counted the 100K customer rows, it discarded the NL side (lines 3, 4, 7, and 8, marked with -) and proceeded with the hash join. The Starts of ORDERS_X1 is 0, so the NL side never ran. The count statement forced with USE_HASH finished in memory with Used-Mem 6930K (0), and USE_MERGE placed a SORT JOIN (sorting the 2M orders rows) under MERGE JOIN. Without a hint, the same count statement chose an NL join with orders as the outer side that repeated an INDEX UNIQUE SCAN of CUSTOMERS_PK 2M times (Starts 2000K).
SQL Server chose Hash Match (Inner Join) for the aggregation by region, but before that it aggregated the 2M orders rows by cust_id (Hash Match (Aggregate), 100K rows) to shrink the join input. With OPTION (MERGE JOIN), a Sort of the pre-aggregated side is attached under Merge Join, and the 50-customer statement ran as Nested Loops … WITH UNORDERED PREFETCH.
KDBS ANALYZE shows the join method as step names.
step 0 Range orders AS o opens=1 examined=1079 matched=1000 sel=92% pages=14 range_stopped_early=1
step 1 Probe customers AS c opens=1000 examined=1000 matched=1000 sel=100% pages=1000 memo_hits=1
In the statement that joins customers to 1,000 orders, a Probe that looks up the customer by tuple key opened 1,000 times (opens=1000). This matches the inner repetition of an NL join. When it tried to join on a column without an index (c.join_dt = o.ord_dt), it failed with statement exceeded its row-touch budget of 3000000 tuples. A join that re-reads the inner side for every outer row exceeded the row access limit (max_rows_touched).
Configuration and Checks
-- PostgreSQL: compare cost by method (session only)
SHOW work_mem; SHOW hash_mem_multiplier;
SET enable_hashjoin = off; -- see the plan with another method
EXPLAIN (ANALYZE, BUFFERS) SELECT ...; -- Hash Batches, Memoize Hits/Misses
RESET enable_hashjoin;
-- MySQL
SELECT @@join_buffer_size, @@optimizer_switch; -- hash_join, block_nested_loop, batched_key_access
EXPLAIN FORMAT=TREE SELECT ...; -- Inner hash join, Nested loop inner join
SELECT /*+ NO_BNL(o) */ ...; -- turn hash join off (since 8.0.20)
-- Oracle
SELECT /*+ LEADING(c) USE_HASH(o) */ ...;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST +ADAPTIVE')); -- Used-Mem, discarded lines of an adaptive plan
SELECT name, value FROM v$parameter WHERE name IN ('optimizer_adaptive_plans', 'pga_aggregate_target');
-- SQL Server
SELECT ... OPTION (HASH JOIN); -- pin only the method
SELECT ... FROM a INNER LOOP JOIN b ON ...; -- pin the method and the join order together
SELECT granted_memory_kb, used_memory_kb, max_used_memory_kb FROM sys.dm_exec_query_memory_grants;
-- KDBS
ANALYZE SELECT ...; -- step names (Probe, IndexProbe) and opens
Related Scenarios
| Topic | PostgreSQL | Oracle | SQL Server |
|---|---|---|---|
| NL join vs hash join | 06 | 06 | 06 |
| Driving set and join order | 05 | 05 | 05 |
| Range join: NL vs sort merge | 11 | ||
| Outer join and the hash Build side | 12 | 12 | 12 |
| Top-N join: hash vs index-order NL | 13 | 13 | 13 |
| Join predicate pushdown | 18 | ||
| Memoize | 20 |
NOTE Defaults and behavior are based on PostgreSQL 17, MySQL 8.0 and 8.4, Oracle 23, SQL Server 2022, and KDBS v3.4, and can vary by version. The MySQL entries follow the manual because there is no sandbox.