Skip to content
Silver 8 min read · spark.sql.join.preferSortMergeJoin 2 practice problems ↓

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

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 typeReturns
innerOnly rows with a match on both sides
left / right outerEvery row of one side, with nulls where the other side has no match
full outerEvery row of both sides, matched where possible
left_semiLeft rows that have at least one match; left columns only, never duplicated
left_antiLeft rows that have no match
crossEvery 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 worksNeedsMain risk
Broadcast hash join
BroadcastHashJoin
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 joinDriverdriver: 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 join
ShuffledHashJoin
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 memoryOut-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 join
SortMergeJoin
Shuffle both sides by key, sort each partition, then walk the two sorted streams together.Equi-join; sortable key typesTwo shuffles and two sorts; skewed keys
Broadcast nested loop join
BroadcastNestedLoopJoin
Broadcast one side and compare every row of the other side with every broadcast row.Any condition, or none; any join typerows × rows comparisons; slow when both sides are large
Cartesian product
CartesianProduct
Pair every partition of one side with every partition of the other, and test the condition on every row pair.Inner or cross joinWork 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:

  1. 1
    Hints. 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.
  2. 2
    Broadcast 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.
  3. 3
    Shuffle hash join if spark.sql.join.preferSortMergeJoin is 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.
  4. 4
    Sort-merge join if the join keys are sortable. Most joins of two large tables end here.
  5. 5
    Cartesian product if it is an inner or cross join.
  6. 6
    Broadcast 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.

Note: with AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → on (the default), the choice is revisited after each shuffle using measured sizes. A planned sort-merge join can become a broadcast hash join when one side turns out small, or a shuffle hash join when every partition is below 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 typeBroadcast hashShuffle hashSort-mergeBroadcast nested loopCartesian
inner, crossYes, either sideYesYesYes, either sideYes
left outer, left semi, left antiRight side broadcastYesYesRight side broadcastNo
right outerLeft side broadcastYesYesLeft side broadcastNo
full outerNoYes (Spark 3.1+)YesYes, but scans data several timesNo

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.

Production patternPySpark · Pick the strategy deliberately: broadcast dimensions, sort-merge big-to-big
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) and method (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?"

Five: broadcast hash, shuffle hash, sort-merge, broadcast nested loop and Cartesian product. For equi-joins: hints first, then broadcast hash if one side is under autoBroadcastJoinThreshold and the join type allows it, then shuffle hash only if preferSortMergeJoin is false and one side is much smaller, then sort-merge, then Cartesian for inner joins, then broadcast nested loop as a fallback. Non-equi joins can only use the nested-loop strategies. Mention that AQE can switch sort-merge to broadcast at runtime, why sort-merge is preferred over shuffle hash (it spills instead of failing), and that full outer joins cannot be broadcast.

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?"
Shuffle hash join builds a hash table per partition that must fit in memory; one big or skewed partition fails the task. Sort-merge sorts with an external sorter that spills to disk and only holds the current key while merging, so it slows down under pressure instead of failing. That robustness is why 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?"
There is no equality, so it is a nested loop (Cartesian product or broadcast nested loop). Add an equality the condition implies: a coarse bucket such as the hour or the user id, exploding each session into the buckets it spans. Join on bucket equality and keep the BETWEEN as an extra condition. It becomes a sort-merge join on the bucket.
Trap"I added /*+ BROADCAST(orders) */ to a LEFT JOIN where orders is the left table. Why is it ignored?"
The preserved side of an outer join cannot be broadcast: each executor would only see its own right-side rows and could not tell whether a left row had no match anywhere. Spark ignores the hint and logs a warning. Broadcast the right side instead, or rewrite the query.

Check yourself

3 questions

Why 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 read
Join 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