Sub topic 12
Choosing join strategies
This chapter assumes you can read a Spark physical plan (see the chapter on EXPLAIN), know what a shuffle is, and have run ANALYZE TABLE on a Delta table. It covers how Spark picks a join strategy, how to check the choice, and when to override it.
Why the join strategy matters
A join must bring matching keys together. How it does that decides how much data crosses the network. A shuffle writes rows to disk, sends them between executors, and reads them back. On large tables it is often the most expensive step in a query. A good strategy avoids or reduces that shuffle.
The main strategies
| Strategy | Plan node | How it works | Best when |
|---|---|---|---|
| Broadcast hash join | `BroadcastHashJoin` (`PhotonBroadcastHashJoin`) | Copies the small side to every executor and builds a hash table. The large side is not shuffled. | One side is small. |
| Shuffled hash join | `ShuffledHashJoin` (`PhotonShuffledHashJoin`) | Shuffles both sides by key, then builds a hash table per partition on one side. | Both sides are large, but each partition of the build side fits in memory. |
| Sort-merge join | `SortMergeJoin` | Shuffles both sides by key, sorts each partition, then merges. | Both sides are large and the build side is too big for memory. |
| Broadcast nested loop join | `BroadcastNestedLoopJoin` | Compares every pair of rows, with one side broadcast. | Non-equality conditions such as `a.x < b.y`. |
| Cartesian product | `CartesianProduct` | Pairs every row with every row. | Almost never what you want. |
Hash-based joins need an equality condition. Non-equi joins fall back to the nested loop strategies, which scale poorly.
The "Photon" prefix in a plan node tells you the operator runs in Photon. If the same join appears without the prefix, that part of the query fell back to the standard Spark engine.
How Spark chooses
By default, the optimizer picks a strategy from size estimates:
- If one side is estimated below
spark.sql.autoBroadcastJoinThreshold(10 MB by default), it broadcasts that side. - Otherwise it uses a shuffle-based join, normally sort-merge.
- Adaptive query execution (AQE) can revise the choice at runtime, once the real sizes of the shuffled data are known.
The size estimates come from table and column statistics, plus filter selectivity. If the statistics are missing or stale, the optimizer may guess a table is large when it is small after filtering. It may also guess it is small when it is not. Broadcasting a side that is really large can cause out-of-memory errors on the driver or executors.
Checking which strategy ran
Start with the plan:
EXPLAIN FORMATTED
SELECT c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01'
GROUP BY c.region;Look for the join node and the Exchange nodes (shuffles) that feed it. A broadcast join shows a BroadcastExchange on the small side and no shuffle on the large side. A sort-merge join shows an Exchange hashpartitioning(...) and a Sort on both sides.
Note that EXPLAIN shows the initial plan. With AQE the final plan can differ. To see what actually ran, open the query in the Query Profile or the Spark UI SQL tab. There the plan is marked as final, and join nodes show row counts and, for shuffles, data sizes.
Keeping the optimizer informed
Good strategy choices depend on accurate statistics. Refresh them after large data changes:
ANALYZE TABLE orders COMPUTE STATISTICS FOR ALL COLUMNS;Delta tables also keep file-level statistics, so the optimizer has a rough table size even without ANALYZE. Column statistics improve estimates for filters and join cardinality. If a query joins on a filtered dimension table, the post-filter size is what matters. Without column statistics the optimizer cannot estimate it well.
Overriding with hints
When you know something the optimizer does not, add a hint. The broadcast hint is the most common:
SELECT /*+ BROADCAST(c) */ c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
GROUP BY c.region;Other join hints are MERGE, SHUFFLE_HASH, and SHUFFLE_REPLICATE_NL. Spark treats a hint as a request. It may ignore one that cannot apply, for example a hash join hint on a non-equi join.
You can also change the threshold for a whole session. The value is in bytes:
# Raise the automatic broadcast limit to 100 MB for this session.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", 100 * 1024 * 1024)Setting it to -1 disables automatic broadcasting.
Adaptive query execution
AQE re-plans the query between shuffle stages. For joins it can do two things:
- Convert a sort-merge join to a broadcast join if the shuffled side turns out to be small.
- Split skewed partitions, where a few keys hold most of the rows, so one task does not run far longer than the rest.
AQE is on by default in current Databricks runtimes. It works best when the original estimate was wrong. However, it can only convert to a broadcast join after the shuffle of that side has already happened. A static hint or accurate statistics avoid that shuffle entirely. The next chapter covers AQE and skew in more detail.
Common problems
- Estimates are wrong, so a sort-merge join runs where a broadcast was possible. Run
ANALYZE TABLE, then re-check the plan. If the small side is a subquery or filtered result, add aBROADCASThint. - Broadcast fails with out-of-memory or a timeout. The hinted side is too large. Remove the hint, or filter or project it down first.
- One task runs far longer than the others. This is data skew. Check the task metrics in the Spark UI, and confirm AQE skew handling is on.
- A join runs as a nested loop. The condition has no equality part. Rewrite the condition to include an equality predicate where possible, for example by joining on a bucketed date plus a range check.
- Join keys have different types. If one side is
INTand the otherSTRING, Spark casts, which can hurt estimates and prevent skipping. Make the types match. - Join not running in Photon. Look for the missing
Photonprefix on the node and see the chapter on fallback.
Exercise
A query joins a 2 TB orders table with a promotions table that holds 40 MB after a filter. The plan shows a SortMergeJoin with an Exchange on both sides, and promotions has never had ANALYZE TABLE run. What would you do, and how would you confirm the change worked?
Show answer
Run ANALYZE TABLE promotions COMPUTE STATISTICS FOR ALL COLUMNS so the optimizer can estimate the filtered size. Since 40 MB is above the 10 MB default threshold, also add /*+ BROADCAST(p) */ to the query, or raise spark.sql.autoBroadcastJoinThreshold above 40 MB. 40 MB is small enough to broadcast safely. Confirm with EXPLAIN FORMATTED that the join is now a BroadcastHashJoin (or PhotonBroadcastHashJoin) with a BroadcastExchange on promotions and no Exchange on orders. Then compare run time and shuffle bytes in the Query Profile.