// troubleshooting guide

Nested loop, hash and merge joins

A plan joins tables with nested loops, a hash table or a merge of sorted inputs. Each is the best choice for some row counts and a poor one for others. How to read them and what to fix when the wrong one was chosen or the right one has no index to use.

Covers PostgreSQL MySQL SQL Server Oracle

The symptom

There are three ways to join two inputs, and every engine picks among them from its row estimates:

  • Nested loop. For each row of the outer input, look up the matching rows in the inner input. Very fast for a few outer rows with an index on the inner side. The inner side runs once per outer row, so the cost grows with the outer row count.
  • Hash join. Read one input completely into an in-memory hash table (the build side), then read the other (the probe side) and look each row up. Good for large inputs with no useful index. Needs memory for the build side.
  • Merge join. Walk two inputs that are sorted on the join key side by side. Cheap when both arrive sorted from indexes; otherwise it pays for sorts first.

None of them is bad. A join is slow when the method does not suit the real row counts, or when a nested loop has no index for its inner side. The query plan viewer flags nested loops that run their inner side many times, hash joins built on the larger input and MySQL joins that fall back to the join buffer. The examples use a shop schema with 20,000 customers, 400,000 orders and 800,000 order items.

Diagnose it

A join with no index on the join column

The most common slow join is a lookup of child rows where the foreign key column has no index. A foreign key constraint does not create one on PostgreSQL, SQL Server or Oracle. To find one customer's orders, the engine reads every order:

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.email, o.order_id, o.total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.email = '[email protected]';
Gather  (cost=1417.01..8005.27 rows=20 width=31) (actual rows=20.00 loops=1)
  Workers Planned: 2
  Workers Launched: 2
  ->  Hash Join  (cost=417.01..7003.27 rows=8 width=31) (actual rows=6.67 loops=3)
        Hash Cond: (o.customer_id = c.customer_id)
        ->  Parallel Seq Scan on orders o  (cost=0.00..6148.67 rows=166667 width=14) (actual rows=133333.33 loops=3)
        ->  Hash  (cost=417.00..417.00 rows=1 width=25) (actual rows=1.00 loops=3)
              Buckets: 1024  Batches: 1  Memory Usage: 9kB
              ->  Seq Scan on customers c  (cost=0.00..417.00 rows=1 width=25) (actual rows=1.00 loops=3)
                    Filter: ((email)::text = '[email protected]'::text)
                    Rows Removed by Filter: 19999
SET STATISTICS IO ON;
GO
SELECT c.Email, o.OrderId, o.Total
FROM dbo.Customers AS c
JOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId
WHERE c.Email = '[email protected]';
Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0
Table 'Customers'. Scan count 1, logical reads 115, physical reads 0
EXPLAIN PLAN FOR
SELECT c.email, o.order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE c.email = '[email protected]';

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation          | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT   |           |    22 |   924 |   685   (1)| 00:00:01 |
|*  1 |  HASH JOIN         |           |    22 |   924 |   685   (1)| 00:00:01 |
|*  2 |   TABLE ACCESS FULL| CUSTOMERS |     1 |    27 |    34   (0)| 00:00:01 |
|   3 |   TABLE ACCESS FULL| ORDERS    |   400K|  5859K|   650   (1)| 00:00:01 |

A hash join over a full scan of the larger table, to return about 20 rows, is the pattern to look for.

MySQL: a reversed join, or Using join buffer

MySQL prefers nested loops with an index on the inner table. With no index on orders.customer_id it cannot look up a customer's orders, so it turns the join round: it reads every order and looks up each order's customer by primary key.

EXPLAIN SELECT c.email, o.order_id, o.total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.email = '[email protected]'\G
table: o
 type: ALL
  key: NULL
 rows: 398228
Extra: NULL
table: c
 type: eq_ref
  key: PRIMARY
 rows: 1
Extra: Using where

When neither table has an index on the join column, MySQL reads both in full and joins them through the join buffer, which the plan reports in Extra:

EXPLAIN SELECT c.customer_id, o.order_id
FROM customers AS c
JOIN orders AS o ON o.order_date = c.created_at\G
table: c
 type: ALL
  key: NULL
 rows: 19965
Extra: NULL
table: o
 type: ALL
  key: NULL
 rows: 398228
Extra: Using where; Using join buffer (hash join)

MariaDB prints the same condition as Using join buffer (flat, BNL join). Either way it says that the join found no index to use.

A nested loop that runs more often than planned

In a plan with actual counts, the inner side of a nested loop shows how many times it ran: loops in PostgreSQL and MySQL, Number of Executions in SQL Server, Starts in Oracle. Compare it with the rows the optimizer expected from the outer side:

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT o.order_id, i.product_id, i.quantity
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.customer_id = 1 AND o.status = 'pending';
Gather  (cost=1000.42..10115.80 rows=868 width=12) (actual rows=8000.00 loops=1)
  Workers Planned: 2
  Workers Launched: 2
  ->  Nested Loop  (cost=0.42..9029.00 rows=362 width=12) (actual rows=2666.67 loops=3)
        ->  Parallel Seq Scan on orders o  (cost=0.00..6982.00 rows=181 width=4) (actual rows=1333.33 loops=3)
              Filter: ((customer_id = 1) AND ((status)::text = 'pending'::text))
              Rows Removed by Filter: 132000
        ->  Index Scan using order_items_pkey on order_items i  (cost=0.42..11.29 rows=2 width=12) (actual rows=2.00 loops=4000)
              Index Cond: (order_id = o.order_id)
              Index Searches: 4000

The optimizer chose the loop for the few hundred orders it expected. Ten times as many arrived, and the index on order_items was searched once for each. Each search is cheap; the plan is slow only if the count is far beyond what was planned. The cause is the row estimate, not the loop.

The build side of a hash join

A hash join should build its hash table from the smaller input. In PostgreSQL the build side is the input under the Hash node; in SQL Server it is the upper input of the Hash Match; in Oracle the first child of HASH JOIN.

SET max_parallel_workers_per_gather = 0;

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.country, count(*)
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
GROUP BY c.country;
HashAggregate  (cost=12149.22..12149.27 rows=5 width=11) (actual rows=5.00 loops=1)
  ->  Hash Join  (cost=617.00..10149.22 rows=400000 width=3) (actual rows=400000.00 loops=1)
        Hash Cond: (o.customer_id = c.customer_id)
        ->  Seq Scan on orders o  (cost=0.00..8482.00 rows=400000 width=4) (actual rows=400000.00 loops=1)
        ->  Hash  (cost=367.00..367.00 rows=20000 width=7) (actual rows=20000.00 loops=1)
              Buckets: 32768  Batches: 1  Memory Usage: 1038kB
              ->  Seq Scan on customers c  (cost=0.00..367.00 rows=20000 width=7) (actual rows=20000.00 loops=1)

Here 20,000 customers are hashed and 400,000 orders probe the table, which is the right way round. When the estimates are wrong the engine can hash the large side by mistake. The signs are a Hash node with far more actual rows than estimated, and Batches above 1, meaning the table spilled to disk.

Fix it

Index the join column on the many side

Create an index on the foreign key column. The join becomes a nested loop that reads only the matching rows:

CREATE INDEX orders_customer_idx ON orders (customer_id);

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.email, o.order_id, o.total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.email = '[email protected]';
Nested Loop  (cost=4.60..509.18 rows=20 width=31) (actual rows=20.00 loops=1)
  ->  Seq Scan on customers c  (cost=0.00..417.00 rows=1 width=25) (actual rows=1.00 loops=1)
        Filter: ((email)::text = '[email protected]'::text)
        Rows Removed by Filter: 19999
  ->  Bitmap Heap Scan on orders o  (cost=4.60..91.95 rows=23 width=14) (actual rows=20.00 loops=1)
        Recheck Cond: (c.customer_id = customer_id)
        Heap Blocks: exact=20
        ->  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.60 rows=23 width=0) (actual rows=20.00 loops=1)
              Index Cond: (customer_id = c.customer_id)
              Index Searches: 1
CREATE INDEX orders_customer_idx ON orders (customer_id);

EXPLAIN SELECT c.email, o.order_id, o.total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.email = '[email protected]'\G
table: c
 type: ALL
  key: NULL
 rows: 20151
Extra: Using where
table: o
 type: ref
  key: orders_customer_idx
 rows: 22
Extra: NULL
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId) INCLUDE (Total);
GO
SELECT c.Email, o.OrderId, o.Total
FROM dbo.Customers AS c
JOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId
WHERE c.Email = '[email protected]';
Table 'Orders'. Scan count 1, logical reads 3, physical reads 0
Table 'Customers'. Scan count 1, logical reads 115, physical reads 0
CREATE INDEX orders_customer_idx ON orders (customer_id);

EXPLAIN PLAN FOR
SELECT c.email, o.order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE c.email = '[email protected]';

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation                    | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT             |                     |    22 |   924 |    56   (0)| 00:00:01 |
|   1 |  NESTED LOOPS                |                     |    22 |   924 |    56   (0)| 00:00:01 |
|   2 |   NESTED LOOPS               |                     |    22 |   924 |    56   (0)| 00:00:01 |
|*  3 |    TABLE ACCESS FULL         | CUSTOMERS           |     1 |    27 |    34   (0)| 00:00:01 |
|*  4 |    INDEX RANGE SCAN          | ORDERS_CUSTOMER_IDX |    22 |       |     2   (0)| 00:00:01 |
|   5 |   TABLE ACCESS BY INDEX ROWID| ORDERS              |    22 |   330 |    22   (0)| 00:00:01 |

The customer is still found by scanning customers, porque email has no index either; that is a separate full table scan to fix. The missing foreign key index snippet lists every foreign key without a supporting index.

Fix the estimate behind a wrong method

When a nested loop runs many times more than planned, or a hash join built the wrong side, find the operator below it where estimated and actual rows diverge and correct that: refresh statistics, add extended statistics for related columns, or deal with a sniffed parameter. The join method then corrects itself. See row estimate mismatch.

Make both join columns the same type

A join between columns of different types can leave the index on one side unusable, which looks exactly like a missing index. Check the declared types before adding anything; the details are under implicit conversions.

When to leave it alone

A hash join between two large tables that the query has to read in full is the correct plan, and so is a nested loop that runs a few hundred indexed lookups. Do not force a join method with hints because one looks wrong by name. Judge by the numbers: rows in, times executed, and whether the inner side used an index.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Identify the join method and which input is the outer or build side.
  2. For a nested loop, read how many times the inner side ran and whether it used an index.
  3. For a hash join, check that the build side is the smaller input and that it stayed in memory.
  4. Compare estimated and actual rows on both inputs.
  5. Index the join column of the table being looked up, usually the foreign key.
  6. Check that both join columns have the same data type.
  7. Capture the plan again and compare rows read.

Questions that come up

Which join type is fastest?

It depends on the row counts. A nested loop is fastest when a few rows drive indexed lookups. A hash join is fastest when both inputs are large and unsorted. A merge join is fastest when both inputs already arrive sorted on the join key. The optimizer chooses from its estimates, so a wrong estimate gives a wrong choice.

Why is my nested loop slow?

Either the inner side has no index on the join column, so each loop scans, or the loop runs far more times than the optimizer planned because the outer row estimate was too low. The plan shows both: the access method on the inner side and its execution count.

Do foreign keys create indexes automatically?

MySQL InnoDB creates an index on the referencing column if none exists. PostgreSQL, SQL Server and Oracle do not: the primary key side is indexed, the foreign key column is not unless you add an index yourself.

What does Using join buffer mean in MySQL?

MySQL found no index on the join column of that table, so it reads the table once and matches rows through an in-memory buffer, with a hash join in MySQL 8 or a block nested loop in MariaDB and older versions. An index on the join column usually replaces it with an indexed lookup.

Should I use join hints to force a hash join or a loop?

Rarely. A hint fixes the method for every future data size and parameter value, including the ones where it is wrong. Correcting the row estimate or adding the missing index lets the optimizer make the choice and keep making it as the data changes.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.