Skip to content
Silver 6 min read 2 practice problems ↓

Join hints and slow non-equi joins

Spark usually picks a good join strategy by itself, but not always: a table it thinks is large, a range join that falls back to comparing every row with every row. This lesson shows how to steer it with hints, how to rewrite a slow non-equi join, and how to check what Spark really ran.

Step 2 · Spark internals · Silver · Shuffles and joins, lesson 4 of 5

Read first: Join strategies (skip if you know it)

In plain words first

Spark usually picks a good way to join, the way a satnav usually picks a good route. A hint is you saying "take the motorway". The satnav follows if the road exists, and ignores you if it does not. This lesson shows when to give that instruction, and how to check which way Spark really went.

Hints

PySparkSpark SQL · Asking for a strategy
orders.join(customers.hint("broadcast"), "customer_id")      # BroadcastHashJoin
orders.join(customers.hint("merge"), "customer_id")          # SortMergeJoin
orders.join(customers.hint("shuffle_hash"), "customer_id")   # ShuffledHashJoin
events.join(sessions.hint("shuffle_replicate_nl"),
            events.ts.between(sessions.start, sessions.end))  # CartesianProduct
SELECT /*+ BROADCAST(c) */ *
FROM orders o JOIN customers c ON o.customer_id = c.customer_id;

SELECT /*+ MERGE(c) */ *
FROM orders o JOIN customers c ON o.customer_id = c.customer_id;

SELECT /*+ SHUFFLE_HASH(c) */ *
FROM orders o JOIN customers c ON o.customer_id = c.customer_id;

SELECT /*+ SHUFFLE_REPLICATE_NL(s) */ *
FROM events e JOIN sessions s ON e.ts BETWEEN s.start AND s.end;

A hint is a request, not an order. Spark ignores a hint it cannot honour, such as broadcasting the preserved side of an outer join or a 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 → hash join on a non-equi condition, and logs a warning. MERGEJOIN and SHUFFLE_MERGE are aliases of MERGE.

Making a slow non-equi join fast

  • OR across two keys — a.id = b.id OR a.email = b.email has no single equality, so it becomes a nested loop. Rewrite it as two equi-joins and union the results (deduplicating if a row can match both ways).
  • Range joins — Matching an IP to an IP range, or an event to a time window, has no equality. Add one the condition already implies: a coarse bucket (the /16 prefix of the IP, the hour of the timestamp). Explode each range into the buckets it covers, join on bucket equality, and keep the range test as an extra condition. The join becomes a sort-merge joinsort-merge join: Spark's default join for two large tables: both sides are shuffled and sorted by the key, then matched in one pass. Learn more → on the bucket.
  • Functions on the key — A join on lower(a.code) = b.code is still an equi-join, but nothing about it can use bucketingbucketing: Writing a table pre-split by a key into a fixed number of files, so later joins on that key skip the shuffle. Learn more → or existing partitioning. Normalise the key once, before the join.

Check what Spark chose

Run explain() and find the join node in the physical plan. What sits under it tells you which strategy Spark picked:

In the planWhat it means
SortMergeJoin, with Exchange and Sort under both sidesThe default for two large tables. Both sides are shuffled and sorted: expensive, but it scales.
BroadcastHashJoin, with BroadcastExchange under one sideThe small side is copied to every executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more →, so the big side is not shuffled. Usually the fastest.
BroadcastNestedLoopJoin or CartesianProduct on two large inputsRed flag: every row is compared with every row. Usually a missing or non-equi join condition.

With AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → on, the plan can change while the query runs, so explain() before execution may not be the final answer. The SQL tab of the Spark UI shows the plan that actually ran.

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: Ask for each join strategy with a hint, and see which one Spark actually plans.

ExplorePySpark · Ask for each strategy with a hint and see what Spark plans
import contextlib, io, re
from pyspark.sql import functions as F

STRATEGY = re.compile(r"(BroadcastHashJoin|ShuffledHashJoin|SortMergeJoin"
                      r"|BroadcastNestedLoopJoin|CartesianProduct)")


def strategy(df):
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        df.explain()
    return STRATEGY.search(buf.getvalue()).group(1)


big = spark.range(0, 1_000_000).withColumnRenamed("id", "k")
small = spark.range(0, 100).withColumnRenamed("id", "k")

print("no hint:", strategy(big.join(small, "k")))
for hint in ["broadcast", "merge", "shuffle_hash", "shuffle_replicate_nl"]:
    print(f"{hint}:", strategy(big.join(small.hint(hint), "k")))

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
print("threshold off:", strategy(big.join(small, "k")))
small2 = small.withColumnRenamed("k", "k2")
print("non-equi (k < k2):", strategy(big.join(small2, F.col("k") < F.col("k2"))))

Output from a real run

no hint: BroadcastHashJoin
broadcast: BroadcastHashJoin
merge: SortMergeJoin
shuffle_hash: ShuffledHashJoin
shuffle_replicate_nl: CartesianProduct
threshold off: SortMergeJoin
non-equi (k < k2): CartesianProduct

What to notice:

  • Without a hint, Spark broadcasts the 100-row table on its own: it is under the 10 MB threshold.
  • Each hint gets the strategy it names; shuffle_replicate_nl shows up as CartesianProduct.
  • With the threshold off, Spark falls back to SortMergeJoin. A join on k < k2 (not equality) can only be a nested loop or Cartesian product.

Common mistakes

  • Not noticing a nested loop — A non-equi condition on two large tables quietly turns into rows × rows comparisons.
  • Expecting a hint to always win — Spark drops hints that the join type or condition cannot support.
  • Trusting explain() before the run with AQE on — AQE can switch a sort-merge join to 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 → at run time. The SQL tab of the Spark UI shows the plan that actually ran.

Key takeaways

  • A hint is a request: BROADCAST, MERGE, SHUFFLE_HASH, SHUFFLE_REPLICATE_NL, in that priority.
  • Spark ignores a hint it cannot honour, and logs a warning.
  • Non-equi joins on large tables become nested loops: add an equality key, or broadcast the small side.
  • Find the join node in explain(); with AQE, check the SQL tab for the plan that ran.

Interview prep

THE QUESTION

"A join on ip BETWEEN range_start AND range_end between two large tables runs for hours. What is happening, and how do you fix it?"

With no equality in the condition, Spark can only use a nested-loop strategy, comparing every row with every row. Fixes: broadcast the ranges table if it is small enough; otherwise add an equality to bucket the data, for example join on a coarse key such as the first octet or the hour, and keep the BETWEEN as an extra condition, so Spark can use a sort-merge or hash join on the bucket key. Confirm with explain() that the join node changed from BroadcastNestedLoopJoin or CartesianProduct.

Avoid: "I add a BROADCAST hint to every join" without checking the table sizes, the join type, or what explain() shows afterwards.

Follow-ups · answer out loud, then open

Follow-up"When would Spark ignore a BROADCAST hint?"
When it cannot honour it: for example broadcasting the side whose unmatched rows a left or full outer join must keep, or a strategy that the join condition does not support. Spark logs a warning and picks a strategy by its usual rules.
Scenario"Customers can match on id or on email. The join with OR is very slow. What do you do?"
An OR across two keys has no single equality, so Spark falls back to a nested loop. Rewrite it as two equi-joins, one on id and one on email, union the results, and deduplicate pairs that matched both ways.
Trap"explain() shows SortMergeJoin, so that is what ran."
With adaptive query execution on, Spark can switch a sort-merge join to a broadcast join at run time once it sees the real sizes. The SQL tab in the Spark UI shows the final plan.

Check yourself

3 questions

Which strategy does a join on e.ts BETWEEN s.start AND s.end use when neither side is small?

Show the answer

CartesianProduct, for an inner join. There is no equality, so only nested-loop strategies apply; for an inner join with no broadcastable side, that is a Cartesian product.

Both sides of a join are hinted, one MERGE and one SHUFFLE_HASH. What wins?

Show the answer

MERGE. The priority is BROADCAST, MERGE, SHUFFLE_HASH, SHUFFLE_REPLICATE_NL.

With AQE on, where do you see the join strategy that actually ran?

Show the answer

The SQL tab of the Spark UI after the run. AQE can change the plan while the query runs; the SQL tab shows the final plan.

Practise this

Interview problems on joins, graded on hidden tests

Keep going

Up next · Shuffles and joins · lesson 5 of 5 · 6 min read
Broadcast joins
Ship a small table to every executor and skip the shuffle, and when broadcasting backfires.

Related lessons

Previous: Join strategies

Primary sources: Join strategy hints · Performance tuning