Sub topic 6
Recognizing join methods
This chapter assumes you can run EXPLAIN PLAN and DBMS_XPLAN.DISPLAY, and that you know how to read plan indentation and execution order from the earlier chapters. You should also know the difference between an access path and a join.
What a join method is
A join combines two row sources. A row source is a table, an index scan, or the result of an earlier join. Oracle joins only two row sources at a time. A query over four tables becomes a chain of three joins, and each one has two decisions:
- The join order: which row source is first and which is second.
- The join method: the algorithm that matches rows from the two sources.
The three main methods are nested loops, hash join, and sort merge join. Each appears in the plan as an operation with exactly two children. The order of the children matters, because it tells you which input plays which role.
Nested loops
A nested loops join reads one row from the first child, called the outer or driving row source. For each of those rows, it runs the second child, the inner row source, to find the matching rows. The inner side is executed many times.
A typical plan for an indexed lookup looks like this:
------------------------------------------------------
| Id | Operation | Name |
------------------------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | NESTED LOOPS | |
| 2 | NESTED LOOPS | |
| 3 | TABLE ACCESS FULL | EMPLOYEES |
|* 4 | INDEX UNIQUE SCAN | DEPT_ID_PK |
| 5 | TABLE ACCESS BY INDEX ROWID | DEPARTMENTS |
------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
4 - access("D"."DEPARTMENT_ID"="E"."DEPARTMENT_ID")Operation 3 is the driving row source. Operation 4 is the inner lookup. It runs once for each row that operation 3 returns, and the join condition appears as an access predicate on the index. The two stacked NESTED LOOPS lines are normal in recent releases. Oracle can fetch the index entries first and then visit the table rows in batches. Read it as one logical nested loops join, with the table access to DEPARTMENTS as the second half of the inner lookup.
Nested loops works well when the outer row source is small and the inner side has a selective index. It works badly when the outer side returns far more rows than expected. The inner side then runs that many times.
Hash join
A hash join reads the first child completely and builds an in-memory hash table on the join key. This is the build input. Then it reads the second child one row at a time and looks each row up in the hash table. This is the probe input. Each child runs once.
-----------------------------------------------
| Id | Operation | Name |
-----------------------------------------------
| 0 | SELECT STATEMENT | |
|* 1 | HASH JOIN | |
| 2 | TABLE ACCESS FULL| DEPARTMENTS |
|* 3 | TABLE ACCESS FULL| EMPLOYEES |
-----------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
1 - access("D"."DEPARTMENT_ID"="E"."DEPARTMENT_ID")
3 - filter("E"."SALARY">10000)The first child (DEPARTMENTS) is the build side, and the second child (EMPLOYEES) is the probe side. The optimizer normally puts the smaller row source on the build side. Three facts help you recognize and judge hash joins:
- A hash join needs an equality condition. Look for
access(... = ...)on theHASH JOINline. - The hash table lives in session memory (PGA). If it does not fit, Oracle writes partitions to temporary space. With
ALLSTATS, a largeUsed-Tmpvalue in the memory columns shows this. - Full scans on both inputs are normal here. A hash join is not a sign of a missing index, because it is designed to process large volumes in bulk.
Sort merge join
A sort merge join sorts both inputs on the join key and then walks through them together, like merging two sorted lists. In the plan, each input sits under a SORT JOIN operation:
-----------------------------------------------
| Id | Operation | Name |
-----------------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | MERGE JOIN | |
| 2 | SORT JOIN | |
| 3 | TABLE ACCESS FULL| DEPARTMENTS |
|* 4 | SORT JOIN | |
| 5 | TABLE ACCESS FULL| EMPLOYEES |
-----------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
4 - access("D"."DEPARTMENT_ID"="E"."DEPARTMENT_ID")
filter("D"."DEPARTMENT_ID"="E"."DEPARTMENT_ID")The same predicate appears twice on the second SORT JOIN. That is normal for a merge join and is not an error. If an input is already ordered, for example from an index scan, Oracle can skip the sort for that side. Sort merge is less common than the other two. It is mostly chosen when the join uses an inequality such as >=, which a hash join cannot handle, or when the inputs are already sorted.
Join variants you will see
The method name can carry a suffix that describes the kind of join:
| Plan operation | Meaning |
|---|---|
| `HASH JOIN OUTER` | Outer join. Rows from the preserved table are kept even without a match. |
| `HASH JOIN RIGHT OUTER` | The preserved table is on the probe side, so Oracle builds the hash table on the other table. |
| `HASH JOIN SEMI` / `NESTED LOOPS SEMI` | An `EXISTS` or `IN` subquery. Each outer row is returned at most once. |
| `HASH JOIN ANTI` / `NESTED LOOPS ANTI` | A `NOT EXISTS` or `NOT IN` subquery. |
| `MERGE JOIN CARTESIAN` | No join condition between the two sources. Every row is paired with every row. |
A Cartesian join is often a symptom: a missing join condition in the SQL, or a table the optimizer wrongly believes has one row. The BUFFER SORT operation under it holds the rows from the second source in memory. It does not sort anything.
Confirming the method with runtime statistics
The estimated plan shows which join method Oracle intends to use. The Starts column from ALLSTATS LAST shows what it actually did. To compare methods, force each one with hints and look at the work done:
SELECT /*+ GATHER_PLAN_STATISTICS LEADING(d e) USE_NL(e) */
e.last_name, d.department_name
FROM hr.departments d
JOIN hr.employees e ON e.department_id = d.department_id
WHERE d.location_id = 1700;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(format => 'ALLSTATS LAST'));LEADING(d e) sets the join order, and USE_NL(e) asks for nested loops with e as the inner table. Replace USE_NL(e) with USE_HASH(e) or USE_MERGE(e) to compare. These hints are for experiments. A hint is a request, and Oracle ignores one it cannot honor, for example a hash join on a non-equality condition. Always check the resulting plan.
In the output, read the Starts column on the inner side of a nested loops join. If the outer side returned 27 rows, the index scan under it should show Starts of 27. If A-Rows on the outer side is far greater than E-Rows, the inner side runs far more often than the optimizer planned. This is the most common reason a nested loops plan is slow.
Choosing between the methods
The following table shows what each method needs and where it performs well.
| Method | Join condition | Best when | Typical weakness |
|---|---|---|---|
| Nested loops | Any | Few outer rows, indexed inner lookup | Cost grows with the outer row count |
| Hash join | Equality only | Large inputs, no useful index | Memory use, spill to temp |
| Sort merge | Equality or inequality | Pre-sorted inputs, inequality joins | Sorting cost on both sides |
The diagram shows how to decide which method you are looking at and what to check next.
Common errors when reading join methods
- Reading the second child as the driving table in a nested loops join. The first child is the outer source, and the second runs once per outer row.
- Calling an inner-side full scan a missing index without checking
Starts. - Assuming a hash join is wrong because it scans both tables fully. For large inputs it is usually the right choice.
- Ignoring
MERGE JOIN CARTESIAN. Check the SQL for a missing join condition first. - Trusting a hint to give you a method. Compare the new plan against what you asked for.
Exercise
A plan shows NESTED LOOPS with a TABLE ACCESS FULL on EMPLOYEES as its first child and an INDEX RANGE SCAN on the second child. ALLSTATS LAST shows E-Rows of 10 and A-Rows of 5000 on the first child, and Starts of 5000 on the index scan. What went wrong, and which join method would you test as an alternative?
Show answer
The optimizer expected 10 outer rows but got 5000, so it chose nested loops for a small driving set. The index range scan ran 5000 times instead of 10. Test a hash join, for example with LEADING and USE_HASH hints, because it reads each input once. Also look at the statistics or predicates behind the misestimate on the first child.
Exercise
Why can a hash join not be used for the condition e.salary >= j.min_salary, and which two join methods remain?
Show answer
A hash join looks up each probe row by hashing the join key, so it needs an equality condition. An inequality gives no single hash value to look up. Nested loops and sort merge join can both handle inequality conditions.