Join strategies
Two queries with the same join can take seconds or hours, depending on how Spark carries the join out. This lesson explains the five join strategies, the order in which Spark considers them, and why sort-merge is its safe default for two large tables.
Step 2 · Spark internals · Silver · Shuffles and joins, lesson 3 of 5
On this page
Read first: Narrow vs wide transformations (skip if you know it)
In plain words first
Matching 500 homework sheets to 500 names: if the name list is short, photocopy it for every desk and let each desk match its own pile (a broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more → join). If both are long, everyone sorts their pile, then the piles are merged in one pass (sort-merge). If the rule is "handed in within a week" rather than "same name", every sheet meets every name (a nested loop). How Spark matches is the join strategy.
Join types vs join strategies
| Join type | Returns |
|---|---|
inner | Only rows with a match on both sides |
left / right outer | Every row of one side, with nulls where the other side has no match |
full outer | Every row of both sides, matched where possible |
left_semi | Left rows that have at least one match; left columns only, never duplicated |
left_anti | Left rows that have no match |
cross | Every combination of left and right rows |
The type is part of what your query means. The strategy is an execution choice Spark makes during physical planning: the same inner join can run as any of the five strategies depending on table sizes, the join condition, configs and hintshint: A request in a query, such as BROADCAST, that steers how Spark runs a join. Spark ignores a hint it cannot honour. Learn more →. The PySpark join and left_semi / left_anti lessons cover the types; this lesson covers the strategies.
The five strategies
| Strategy (plan node) | How it works | Needs | Main risk |
|---|---|---|---|
Broadcast hash joinBroadcastHashJoin | Copy the small side to every executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more →, build a hash table from it, stream the large side through it. No shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more →. | Equi-join; one side small; not a full outer join | Driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more → and executor memory when the "small" side is not small |
Shuffle hash joinShuffledHashJoin | Shuffle both sides by key. In each partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more →, build a hash table from the smaller side and probe it with the other. No sort. | Equi-join; the build side of every partition fits in memory | Out-of-memory on one large or skewedskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more → partition |
Sort-merge joinSortMergeJoin | Shuffle both sides by key, sort each partition, then walk the two sorted streams together. | Equi-join; sortable key types | Two shuffles and two sorts; skewed keys |
Broadcast nested loop joinBroadcastNestedLoopJoin | Broadcast one side and compare every row of the other side with every broadcast row. | Any condition, or none; any join type | rows × rows comparisons; slow when both sides are large |
Cartesian productCartesianProduct | Pair every partition of one side with every partition of the other, and test the condition on every row pair. | Inner or cross join | Work and output grow as rows × rows |
An equi-join has at least one equality between a column of each side in its condition (o.customer_id = c.customer_id, possibly ANDed with other conditions). Only equi-joins can use the hash and sort strategies, because those need a key to partition and match on. A condition with no such equality, like e.ts BETWEEN s.start AND s.end, a.x < b.y, or two equalities joined by OR, is a non-equi join and can only run as a nested loop.
How Spark picks one
For an equi-join, Spark walks this list and takes the first strategy that applies:
- 1Hints. If you hinted a strategy and the join supports it, Spark uses it. When both sides carry different hints, the priority is BROADCAST, then MERGE, then SHUFFLE_HASH, then SHUFFLE_REPLICATE_NL.
- 2Broadcast hash join if the join type allows broadcasting a side and that side's estimated size is below
spark.sql.autoBroadcastJoinThreshold(10 MB). If both sides qualify, the smaller is broadcast. - 3Shuffle hash join if
spark.sql.join.preferSortMergeJoinis false (it is true by default), one side is small enough to hash per partition (below the broadcast threshold × the number of shuffle partitions), and it is at least three times smaller than the other side. - 4Sort-merge join if the join keys are sortable. Most joins of two large tables end here.
- 5Cartesian product if it is an inner or cross join.
- 6Broadcast nested loop join as the last resort. It handles every case, even if that means broadcasting a large side.
For a non-equi join the list is shorter: a broadcast hint or a side below the threshold gives a broadcast nested loop join; otherwise an inner or cross join becomes a Cartesian product; otherwise Spark falls back to a broadcast nested loop join anyway.
spark.sql.adaptive.maxShuffledHashJoinLocalMapThreshold (0 by default, so off).Why sort-merge is the default
A shuffle hash join skips the sort, so on paper it is faster. But its hash table for a partition must fit in memory, and one oversized or skewed partition fails the tasktask: The work for one partition in one stage, run on one CPU core. Learn more →. A sort-merge join sorts with an external sorter that spillsspill: Writing data to local disk because it does not fit in memory. Slower, but the job keeps running. Learn more → to disk, and the merge holds only the rows of the current key, so it slows down under pressure instead of failing. That robustness is why Spark prefers it. Shuffle hash join is worth trying when one side is too big to broadcast but small per partition, and keys are not skewed.
Which strategies support which join types
| Join type | Broadcast hash | Shuffle hash | Sort-merge | Broadcast nested loop | Cartesian |
|---|---|---|---|---|---|
| inner, cross | Yes, either side | Yes | Yes | Yes, either side | Yes |
| left outer, left semi, left anti | Right side broadcast | Yes | Yes | Right side broadcast | No |
| right outer | Left side broadcast | Yes | Yes | Left side broadcast | No |
| full outer | No | Yes (Spark 3.1+) | Yes | Yes, but scans data several times | No |
The pattern: the side that must keep unmatched rows is streamed, so only the other side can be the broadcast or build side.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Choose the join strategy on purpose: broadcast the small dimension table, sort-merge the two large tables.
from pyspark.sql import functions as F orders = spark.range(0, 1_000_000).selectExpr( "id AS order_id", "id % 1000 AS product_id") products = spark.range(0, 1000).selectExpr("id AS product_id", "id % 10 AS category") payments = spark.range(0, 1_000_000).selectExpr("id AS order_id", "id % 7 AS method") enriched = (orders # a dimension: copy it to every executor .join(F.broadcast(products), "product_id") .join(payments.hint("merge"), "order_id")) # two large sides: sort-merge enriched.write.mode("overwrite").parquet("lab/join_strategies/enriched") result = spark.read.parquet("lab/join_strategies/enriched") print(result.count(), "rows") result.orderBy("order_id").show(5)
Output from a real run
1000000 rows +--------+----------+--------+------+ |order_id|product_id|category|method| +--------+----------+--------+------+ | 0| 0| 0| 0| | 1| 1| 1| 1| | 2| 2| 2| 2| | 3| 3| 3| 3| | 4| 4| 4| 4| +--------+----------+--------+------+ only showing top 5 rows
What to notice:
- 1,000,000 rows came out: every order found its product and its payment, so no rows were lost or duplicated.
- Each row now has
category(from the broadcast products table) andmethod(from the sort-merge join with payments).
Common mistakes
- Confusing join type with join strategy — A left join is not a strategy. It can run as a broadcast hash, shuffle hash, sort-merge or nested loop join.
- Forcing shuffle hash joins on skewed data — One hot key builds a hash table that does not fit, and the task fails instead of spilling.
Key takeaways
- Join type is what you get; join strategy is how Spark computes it.
- Equi-joins can use broadcast hash, shuffle hash or sort-merge; non-equi joins only nested loops.
- Order: hints, broadcast hash, shuffle hash (if preferred), sort-merge, Cartesian, broadcast nested loop.
- Sort-merge is the default for big tables because it spills to disk instead of failing.
Interview prep
THE QUESTION
"Which join strategies does Spark have, and how does it decide between them?"
Avoid: answering with join types ("inner, left, outer") when the question is about strategies, or saying "Spark always uses sort-merge".
Follow-ups · answer out loud, then open
Follow-up"Why does Spark prefer sort-merge join over shuffle hash join by default?"
spark.sql.join.preferSortMergeJoin is true.Scenario"A join on events.ts BETWEEN sessions.start AND sessions.end between two large tables runs for hours. What do you do?"
Trap"I added /*+ BROADCAST(orders) */ to a LEFT JOIN where orders is the left table. Why is it ignored?"
Check yourself
3 questionsWhy does Spark prefer sort-merge over shuffle hash join by default?
Show the answer
It spills to disk under memory pressure, while a per-partition hash table must fit in memory. spark.sql.join.preferSortMergeJoin is true because sort-merge degrades gracefully.
Which join type can never use a broadcast hash join?
Show the answer
full outer. Both sides must keep unmatched rows, so neither can be the broadcast side.
A 5 MB dimension table is joined to a 2 TB fact table on customer_id, with default settings. Which strategy does Spark pick?
Show the answer
BroadcastHashJoin. The small side is under spark.sql.autoBroadcastJoinThreshold (10 MB by default), so it is broadcast.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Shuffles and joins · lesson 4 of 5 · 6 min readJoin hints and slow non-equi joins
Steer the join strategy with hints, rewrite a join that fell back to a nested loop, and check what Spark really ran.
Related lessons
Previous: Shuffle partitions
Primary sources: Join strategy hints · Performance tuning: join strategy hints