Physical Joins in Apache Spark: A Visual Guide
You want to combine orders with customer details in Spark. The matching rule seems simple, yet the query might spend more time moving records between machines than finding the matches.
Whether you are learning joins for the first time or bringing years of SQL Server experience, the central question is the same: how will matching rows meet, and what will that cost?
This guide explains Spark’s five main batch join strategies with pictures, examples, and a lab. No prior SQL Server experience is required. An optional SQL Server refresher and operator map provide a bridge for developers who already know Nested Loops, Hash Match, and Merge Join. Deeper guidance on memory, skew, statistics, and adaptive execution supports experienced Spark developers too.
Baseline: standard Apache Spark 4.1 batch SQL/DataFrame execution. The hands-on environment is Microsoft Fabric Runtime 2.0, with Spark 4.1 and Delta Lake 4.2, as listed in the runtime documentation. Delta supplies the lab’s table storage; it does not select the join algorithm. Native-engine differences are called out separately. This is not a guide to stateful stream-stream joins.
Validation status: the join examples were validated on Fabric Runtime 2.0. Expected counts and totals below are derived from the data formulas. Plan fragments remain illustrative, not captured output, and this article makes no measured speedup claims.
Choose your reading depth
- Starting directly with Spark? Read the shared foundations and distribution picture below, then jump to the five strategies, skipping the optional SQL Server bridge.
- Moving from SQL Server? Use the same foundations, then the SQL Server refresher and operator map.
- Already know the basics? Start at workload selection, then AQE and the disposable lab. Basic Python and SQL help with the lab; neither is needed for the pictures.
First separate logical joins from physical joins
A table or DataFrame contains rows and named columns. A join combines related rows from two inputs: an order’s customer_id, its join key, identifies the customer whose details it needs.
A logical join defines which rows belong in the answer. A physical join is the algorithm used to produce it; the execution plan is the recipe you inspect. Think of the logical join as the guest-matching rule at a conference and the physical join as the process used to find matching badges. Changing the process must not change who is admitted.
-- Conceptual query, valid in both engines when these tables exist.
SELECT o.order_id, c.segment
FROM orders AS o
INNER JOIN customers AS c
ON o.customer_id = c.customer_id;
INNER JOIN is not a request for a hash join. Either engine can choose a different legal algorithm without changing the answer.
An equi-join matches equal keys, as above. A pure non-equi join has no usable equality key: for example, matching an amount to a price interval.
A join can use both conditions. Suppose a customer changed segments in July. For a June order, match the customer ID, then keep the segment record whose dates cover the order date. Spark can use hash or sort-merge on the ID and check the date range as a residual condition on those candidates. A date condition does not, by itself, require a nested loop.
The logical choices are: inner keeps matches; left/right outer also keeps unmatched rows from the named side; full outer keeps unmatched rows from both. Left semi keeps left rows with a match, left anti keeps those without one, and neither adds right-side columns. Cross requests every combination. These semantics constrain the legal algorithms and build sides.
Three terms recur below:
- Build / probe: construct a key-based lookup from one input, then search it using rows from the other. The streamed input is processed as rows arrive rather than copied in full for this join.
- Fact / dimension: orders are the many events (the fact); customers supply descriptive attributes (the dimension). These labels do not establish either input’s size.
- Spill / skew: spilling uses local disk for supported work that does not fit memory; skew means uneven work, such as one very frequent key.
What Spark adds: getting rows to the same place
Imagine orders are spread across several warehouses. Before a worker can match an order with a customer, it needs access to both records.
Spark has a driver, the coordinating process, and executors, worker processes that run tasks. An execution partition is a slice of records processed by a task in a stage. It is not necessarily a directory partition such as order_date=2026-12-01; the same word is used at two different layers.
For ordinary Spark scans of the lab’s Delta tables, there is no SQL Server-style customer-key B-tree seek to use as an inner lookup for each order. File skipping can reduce scan work, but it is not that per-row indexed lookup. This is why moving an indexed Nested Loops plan’s intuition directly to Spark can be misleading.
Two common ways to bring join inputs together are:
- Shuffle: redistribute records by the join key so matching keys reach compatible execution partitions. Like sending orders and customer cards to the warehouse assigned to each customer.
- Broadcast: distribute a complete small input to participating executors, so tasks can match their existing large-side partitions locally. Like giving each warehouse the same compact customer directory.
The analogy stops at the process boundary: Spark can reuse exchanges, schedule tasks on different executors, spill shuffle/sort data, and adapt a plan. The picture does not promise a permanently assigned machine for each customer.
In an execution plan, distinguish Exchange hashpartitioning(...) from BroadcastExchange. Both move data, but a broadcast exchange is not a hash shuffle. An aggregation after the join can introduce another shuffle, so do not blame every Exchange on the join itself.
Start with SQL Server’s familiar operators
Optional bridge for SQL Server developers. Spark-first readers can continue to the five strategies.
| SQL Server operator | Mechanism | Good starting situation | Main cost or trap |
|---|---|---|---|
| Nested Loops | For each outer row, search the inner input | Few outer rows, especially with a selective inner index seek | Many repeated searches; scans become costly as the outer input grows |
| Merge Join | Walk inputs ordered on equality keys | Ordering exists, or sorting is worthwhile | Sorts can spill; duplicate groups can need a worktable |
| Hash Match (join) | Build a lookup, then probe it | Unsorted equality joins | Build memory, inaccurate estimates, spills to tempdb |
| Adaptive Join | Choose between prepared hash and nested-loops alternatives using a row-count threshold | Eligible batch-mode plans with uncertain cardinality | A specific operator, not arbitrary replanning |
For Nested Loops, an index is like jumping straight to the right name in a customer directory. Ordinary scans of the lab’s Delta tables do not offer that per-order B-tree seek. SQL Server’s disk-backed grace hash processing and memory grants also should not be assumed for Spark’s JVM hash joins. See Microsoft’s join operator explanation.
SQL Server already has parallel exchanges: Repartition Streams with hash partitioning is a useful counterpart to Spark’s Exchange hashpartitioning, and an exchange with broadcast partitioning, such as Distribute Streams (Broadcast), sends every input row to every consumer. These are row-routing analogies, not identical implementations: SQL Server exchanges connect worker threads; Spark’s exchanges operate across execution partitions and executors. The exchange’s name alone does not determine routing; inspect its partitioning type. See Microsoft’s exchange operator explanation.
SQL Server’s Adaptive Join and Spark AQE both use runtime information to improve a decision, but are not equivalent operators.
The operator map
This optional translation table connects the two engines; the next section explains Spark independently. These are the main strategies in standard Spark’s batch planner, not an exhaustive catalog of vendor-native operators or special subquery optimizations. Spark 4.1’s join-selection source documents their capabilities and fallback order.
| Spark strategy | Familiar SQL Server idea | Typical plan label | Principal extra work |
|---|---|---|---|
| Broadcast hash | Hash Match with a replicated build input | BroadcastHashJoin |
Collect/build and distribute one input |
| Shuffled hash | One hash join per corresponding partition pair | ShuffledHashJoin |
Establish compatible distribution, then build local hash tables |
| Sort-merge | Merge Join on ordered partition pairs | SortMergeJoin |
Establish distribution and ordering as needed |
| Broadcast nested loop | Repeated comparison against a replicated input, without an index seek | BroadcastNestedLoopJoin |
Broadcast plus potentially many predicate evaluations |
| Cartesian product | Enumerate row pairs, optionally with a condition | CartesianProduct |
Pair input partitions and evaluate combinations |
AdaptiveSparkPlan is an adaptive wrapper, not a sixth join algorithm.
Understand the five strategies
Each strategy combines a matching mechanism with a way of bringing records together. Spark-first readers need only the shared foundations above, not the SQL Server bridge.
Hash is like placing customer cards into labeled bins and probing the right bin for each order; collisions still require comparing actual keys. Merge is like walking two alphabetized lists together, advancing the list that is behind. Producing those ordered lists can cost more than walking them.
1. Broadcast hash join: copy the small lookup, not the fact
How it works: Spark collects the build input through the driver, constructs a broadcast hash relation, and distributes it for executor-side probes. The streamed input need not be reshuffled just to satisfy this join.
For orders joined to a genuinely small customer segment lookup, avoiding a large orders shuffle can be valuable. Spark still has to read and process the relevant orders, and earlier/later operations may move them.
Plan shape (illustrative):
BroadcastHashJoin [customer_id], [customer_id], Inner, BuildRight
:- Scan orders
+- BroadcastExchange HashedRelationBroadcastMode(...)
+- Scan customers
Use when: an equality join has a supported build side small enough to collect on the driver and copy to every executor, with memory to spare while other work runs.
Costs and risks: driver collection/build time, broadcast distribution, executor hash-table memory, and timeout risk. The build representation can be much larger than compressed files. There is no universal “100 MB is safe” rule; row width, key type, and concurrent work change the budget.
Standard Spark 4.1’s automatic threshold is 10 MiB (10485760 bytes), based on planning statistics, not a measured in-memory ceiling. spark.sql.broadcastTimeout defaults to 300 seconds. A BROADCAST hint can exceed the automatic threshold, but it does not make the input fit or bypass all implementation limits. Inspect actual configuration and broadcast metrics. See Spark’s broadcast documentation.
For ordinary broadcast hash joins:
- Inner joins can build either side.
- Left outer, left semi, and left anti joins can build the right side.
- Right outer joins can build the left side.
- Full outer joins are not supported by this strategy.
These are not universal rules for broadcast nested-loop joins, which have different implementation paths.
Why does left outer build on the right? Picture orders spread across several executors, including order 103 whose customer is missing. With the complete customers lookup broadcast to each executor, the task holding order 103 can check every possible customer match and safely emit that order with null customer details. If orders were broadcast while customers stayed distributed, finding no match in one customer’s partition would not prove that no other partition had a match. Preserving unmatched orders would require additional coordination. This explains Spark’s ordinary broadcast-hash implementation restriction, not an impossibility for every distributed join algorithm.
Broadcast avoids join-key redistribution skew on the streamed side, but it does not cure an already uneven input partition, an expensive predicate, or one order matching millions of duplicate customer rows.
2. Shuffled hash join: distribute first, build locally
How it works: Spark establishes compatible key partitioning, then builds a hash table for one side of each corresponding partition pair. Unlike broadcast, each task needs only its build partition, not the whole dimension. Unlike sort-merge, it does not require sorting both inputs.
Read the plan: in an illustrative ShuffledHashJoin [customer_id], [customer_id], Inner, BuildRight, each task builds its lookup from its partition of the right child and probes it with rows from the left. Trace both children for Exchange hashpartitioning(customer_id, ...) to see which inputs Spark had to redistribute. An input that is already partitioned compatibly may not need a new exchange.
Use when: broadcasting the whole input is unsuitable, but the largest per-task build input fits with a comfortable memory margin and the avoided sort is worthwhile.
Costs and risks: shuffle traffic and partition-local hash memory. The important unit is the largest build partition, not total size divided by partition count. A hot key can invalidate that average; concurrent tasks on one executor compete for memory.
A hypothetical sizing decision, not a result from this lab: suppose a representative build-side shuffle contains 8 GiB across 80 partitions. The average is about 102 MiB, but one partition contains 2 GiB. Now imagine an executor has roughly 3 GiB of headroom for all concurrent join work and runs four tasks at once. An even share would be 768 MiB per task, not 3 GiB; Spark does not reserve that equal share for each task. The 2 GiB input is already a warning, and its in-memory hash representation can be larger still. Neither compressed table size nor the average partition establishes safety.
Standard Spark’s unhinted selection considers estimates, relative input sizes, hash-compatible key types, and spark.sql.join.preferSortMergeJoin, which defaults to true. Hints and AQE can lead to shuffled hash instead. An unsortable key rules out sort-merge; it does not guarantee shuffled hash, which still needs an eligible build side and planner path.
Oversized JVM broadcast/shuffled hash relations can fail with out-of-memory errors; do not assume they automatically switch to a disk-backed hash algorithm like SQL Server’s grace hash processing.
Shuffled hash supports equi-joins across the main logical join types, including full outer, but legal build-side choices and implementation paths depend on join type. It is not a pure range-join algorithm.
3. Sort-merge join: distribute, order, then walk
How it works: Spark brings equal keys into compatible partitions, sorts each input partition when needed, and walks the sorted streams. Matching duplicate-key groups can generate many rows.
Plan shape (illustrative; existing distribution/order can remove nodes):
SortMergeJoin [customer_id], [customer_id], Inner
:- Sort [customer_id ASC NULLS FIRST]
: +- Exchange hashpartitioning(customer_id, ...)
: +- Scan orders
+- Sort [customer_id ASC NULLS FIRST]
+- Exchange hashpartitioning(customer_id, ...)
+- Scan customers
Use when: both inputs are large, keys are orderable, and a broadcast or per-partition hash build is not a good fit. It supports the main equality join types, including full outer.
Costs and risks: shuffle, sorting, and buffering duplicate groups. Sort and buffering can spill to local disk, but spill-capable is not failure-proof: heavy spills, disk exhaustion, skew, and explosive output can still make it slow or fail.
Reading a sorted file does not automatically prove that Spark recognizes the ordering required by the join. Likewise, Hive-style partition directories, Z-Order, liquid clustering, and Fabric V-Order are not B-tree indexes or automatic guarantees of matching hash distribution.
For repeated large joins, compatible catalog bucketing or a supporting DataSource V2 connector’s storage-partitioned join can sometimes remove exchanges. Eligibility depends on connector, transforms, settings, and planner recognition; it is not a drop-in promise for arbitrary Delta tables. Even when a shuffle disappears, a sort may remain. See Spark’s storage-partitioned join documentation.
4. Broadcast nested loop: small lookup, potentially many comparisons
How it works: without an equality key, a hash lookup cannot directly find the matching interval. For each streamed row, Spark may need to test the broadcast records against the predicate.
An order amount matched against four nonoverlapping price bands is a reasonable teaching example:
-- Conceptual Spark SQL; the lab supplies its own disposable tables.
SELECT /*+ BROADCAST(b) */ o.order_id, b.band
FROM orders AS o
JOIN price_bands AS b
ON o.amount >= b.lower_bound AND o.amount < b.upper_bound;
Use when: a required pure non-equi join has a truly tiny comparison input and a manageable candidate-pair count.
Costs and risks: broadcasting plus repeated comparisons, not index seeks. A tiny lookup can still mean substantial CPU against a huge streamed input. Inclusive BETWEEN on adjacent bands can match a boundary twice; keep endpoints explicit.
Broadcast nested loop supports more logical/build-side combinations than broadcast hash, including full outer implementation paths, but some require extra scans or coordination. Do not copy the broadcast-hash build-side table onto it.
It is also a fallback for joins that cannot use better strategies. A large fallback can be unsafe even when neither side qualified for automatic broadcast. Disabling automatic broadcast is not a universal ban on every broadcast fallback.
For large interval datasets, consider a valid additional equality key, such as account ID plus time range. Time bucketing can reduce candidate pairs, but intervals spanning buckets must be represented in every relevant bucket, with a consistent timezone and endpoint convention. Preserve the original range predicate and verify no matches were lost or duplicated. An invalid shortcut is worse than a slow join.
5. Cartesian product: every candidate pair deserves suspicion
How it works: a Cartesian physical operator pairs partitions and enumerates row combinations, possibly evaluating a residual condition. It is not necessarily a conventional hash shuffle of both tables.
An explicit CROSS JOIN does not guarantee this physical operator: Spark may choose broadcast nested loop instead. Conversely, an inner pure non-equi join can use CartesianProduct even though the SQL contains an ON clause.
Use when: a small calendar crossed with a small product set creates an intentionally bounded coverage grid.
Costs and risks: pairwise comparisons and potentially explosive output. Two inputs of one million rows each have a trillion possible pairs before filtering.
The SHUFFLE_REPLICATE_NL hint requests a shuffle-and-replicate nested-loop strategy for eligible inner-like joins; the name is not evidence that the final plan contains two key-based shuffle exchanges.
Correctness traps that no physical strategy fixes
- Many-to-many explosion: if one key occurs 1,000 times on each side, it can produce 1,000,000 inner-join rows. Validate dimension uniqueness; deduplicate only when the business meaning allows it.
- Nulls: ordinary
=does not match nulls. Spark commonly filters null join keys before an inner equality join; inspect forisnotnullin the optimized plan. For an outer join shuffled on a single key, preserved null-key rows can concentrate in one partition. A broadcast join need not shuffle them, and nulls in a composite key do not necessarily share a partition. Null-safe<=>matches nulls and can create a large matching group. NOT INversusNOT EXISTS: nulls in the subquery can change the answer. Null-aware anti-join optimizations have special requirements.- Outer-join filters: take order 103 from Figure 1, which has no matching customer. After a left join,
WHERE c.segment = 'Retail'drops order 103: its null segment does not pass the filter. Put the same test inONalongside the customer-ID match instead, and order 103 survives with a null segment. UseWHEREif you want only Retail matches; useONif you want every order but only Retail customer details. - Key casts: match types deliberately. Spark 4.1’s standard ANSI default can turn malformed casts into errors. Fix the data contract rather than hiding errors to make a plan look faster.
See Spark’s null semantics, null-filter inference rules, and ANSI behavior.
Choose by workload, not by a favorite hint
A hypothetical workload to reason about
A retail team joins orders to customers for segmentation, two large event datasets for attribution, and order amounts to a tiny price-band lookup. Before picking a strategy, ask about the filtered, projected inputs: only the rows and columns reaching the join.
| Question | Why it matters |
|---|---|
| Is there a usable equality key? | Hash and sort-merge need one |
| How large is the candidate build input? | It must fit the appropriate driver/executor or per-task memory budget |
| Is one customer disproportionately common? | Hash partitioning can concentrate work |
| Is the dimension key unique? | Duplicates can multiply the answer |
| Which unmatched rows must survive? | Join semantics restrict strategies and build sides |
| Is distribution or ordering already compatible? | Shuffle or sort work may be avoidable |
Use those answers to choose a first candidate:
| Workload | First candidate to evaluate | Check before adopting |
|---|---|---|
| Large fact plus bounded small dimension on equality | Broadcast hash | Actual build memory, driver pressure, concurrency, supported side |
| Large plus medium equality join | Shuffled hash or sort-merge | Worst build partition versus sort/spill cost |
| Large plus large equality join | Sort-merge as a baseline | Skew, shuffle volume, spills, existing distribution |
| Repeated large join on the same keys | Investigate reusable compatible layout | Connector support, write/maintenance cost, actual missing exchanges |
| Large input plus tiny range lookup | Broadcast nested loop | Comparison count, range overlap, boundaries |
| Two large range inputs | Reduce candidates with valid equality keys or redesign | Exact equivalence, bucket expansion, residual predicate |
| Deliberate tiny all-pairs calculation | Cartesian or broadcast nested loop | Explicit output bound |
Using hints safely: a hint requests a strategy; it does not change the answer or guarantee the operator. Conflicting hints have priority BROADCAST > MERGE > SHUFFLE_HASH > SHUFFLE_REPLICATE_NL. Unsupported hints can be ignored; unlike SQL Server’s inline join hints, do not assume they enforce the same whole-query join-order behavior. Spark documents their scope.
- For broadcast, record actual build/distribution size and time, driver/executor memory pressure, garbage collection, and failures. Broadcast data size is not total executor memory use.
- For shuffled hash, inspect the largest build partition, not just the average or a task’s combined reads from both sides.
- Compare the default and one justified alternative on the same inputs and answer. If memory evidence is missing or headroom doubtful, remove the hint. Retain one only with repeatable evidence and an owner who will revisit it as data grows.
Statistics and AQE: estimated versus executed reality
Estimates are useful, not memory measurements
Spark can use data-source, catalog, and runtime statistics. Inspect EXPLAIN COST or df.explain("cost") before deciding that a filtered input is too large or small.
A usable default: with CBO (cost-based optimization) off, Spark’s basic estimator generally retains the child input’s size for an ordinary residual Filter. But partition pruning or data-source pushdown can change the underlying scan statistics even without CBO. With suitable statistics, CBO can estimate selectivity; AQE can use measured runtime sizes. Neither guarantees an accurate estimate for every predicate. See the basic estimator and partition-pruning statistics update.
For persistent tables, supported ANALYZE TABLE operations can improve catalog statistics; verify the catalog/provider’s support and whether column statistics and cost-based optimization are needed. Delta file min/max statistics used for skipping are not automatically a complete set of optimizer column-cardinality statistics.
Cost-based join reordering is off by default in upstream Spark 4.1: both spark.sql.cbo.enabled and spark.sql.cbo.joinReorder.enabled default to false. The cost-based reorder rule requires both enabled, suitable statistics, and an eligible join shape. Other optimizer rules can still transform joins while it is off. Inspect the whole plan rather than assuming SQL table order determines execution order.
What AQE can change
Adaptive Query Execution, enabled by default in standard Spark 4.1, uses runtime statistics at materialization boundaries to revise eligible remaining work.
| AQE behavior | Potential benefit | Important limit |
|---|---|---|
| Sort-merge to broadcast hash | Avoid sorts and use local shuffle reading where applicable | Already completed shuffle writes are not undone |
| Sort-merge to shuffled hash | Avoid sorting when partition-local hash builds qualify | Governed by partition-size thresholds and eligibility |
| Skewed join partition splitting | Split heavy work and replicate corresponding input pieces | Requires eligible shuffled joins and configured thresholds |
| Post-shuffle coalescing | Reduce many tiny tasks | Does not rescue an unbounded output or every oversized partition |
Standard Spark defaults include spark.sql.adaptive.maxShuffledHashJoinLocalMapThreshold = 0, so that size-threshold-driven conversion is not enabled by a positive budget unless configured. Skew detection uses both a factor over the median partition and an absolute size threshold; the documented defaults are 5 and 256 MiB. Managed settings can differ. These details and broadcast conversion are described in Spark 4.1’s AQE guide.
An initial AdaptiveSparkPlan isFinalPlan=false is not the final answer. Inspect the completed execution’s plan and metrics in the Spark UI. AQE helps, but it does not replace sensible data sizes or make an incorrect join correct.
Fabric native execution: compare a different execution path explicitly
Fabric’s Native Execution Engine uses Apache Gluten and Velox to offload supported operations from Spark’s JVM (Java Virtual Machine) path to native code. This can change operators and memory/spill behavior; unsupported portions can fall back to the JVM, producing a mixed plan.
The lab below disables it to keep standard Spark labels comparable. For a later native comparison, use a separate controlled session with the same data and query. Record the Environment setting, inspect native/fallback diagnostics, and validate results; do not silently mix JVM and native timings. Check the Fabric documentation for the deployed runtime’s support.
A disposable Fabric lab: same answer, different plans
This lab recognizes strategies and verifies equivalent batch-join results. Keep it as a functional exercise, not a timing contest.
1. Set up one isolated session
You need Fabric access, capacity that supports Spark, and permission to create tables in a disposable, schema-enabled lakehouse. Compute and OneLake storage can incur charges.
Create/open an Environment item, select Runtime 2.0, save and publish, attach it to a new notebook, and attach the disposable lakehouse as its default. An attached Environment overrides the workspace runtime. Use the managed libraries; do not install standalone Spark/Delta packages.
Use PySpark as the default cell language. Turn Native Execution Engine off in the lab Environment before starting the session. Do not change a shared production Environment.
The lab creates only dbo.spark_join_lab_orders and dbo.spark_join_lab_customers; dbo resolves in the attached default schema-enabled lakehouse. It refuses to overwrite existing names. Delete only these lab-owned tables at the end if you want to rerun.
Run this PySpark cell to record the baseline and save the settings the lab changes:
from pyspark.sql import functions as F
print("Spark:", spark.version)
assert spark.version.startswith("4.1."), "This lab targets Spark 4.1."
lab_settings = {
"spark.sql.adaptive.enabled": "true",
"spark.sql.shuffle.partitions": "8",
}
if "original_settings" not in globals():
original_settings = {key: spark.conf.get(key) for key in lab_settings}
if "join_lab_created_tables" not in globals():
join_lab_created_tables = []
for key in [
"spark.sql.autoBroadcastJoinThreshold",
"spark.sql.adaptive.enabled",
"spark.sql.adaptive.autoBroadcastJoinThreshold",
"spark.sql.adaptive.maxShuffledHashJoinLocalMapThreshold",
"spark.sql.cbo.enabled",
"spark.sql.cbo.joinReorder.enabled",
"spark.sql.join.preferSortMergeJoin",
"spark.sql.shuffle.partitions",
"spark.sql.ansi.enabled",
]:
print(key, "=", spark.sql(f"SET {key}").first()["value"])
for key, value in lab_settings.items():
spark.conf.set(key, value)
Keep the recorded values with your results. An unset adaptive broadcast threshold falls back to the static broadcast threshold; the SET inspection can display an undefined optional value without assuming it is zero. Eight shuffle partitions is a small-lab choice, not a production recommendation.
The guard captures the original settings once per notebook session. Rerunning setup reapplies the lab settings without replacing the saved pre-lab values; the printed settings on a rerun reflect the current session, not a new original baseline. Keep the first recorded output. To establish a different baseline, finish cleanup and start a fresh session.
2. Create deterministic Delta inputs
Prerequisite: attach the disposable, schema-enabled lakehouse to this notebook and set it as the default lakehouse before running this cell. The dbo table names resolve in that lakehouse, and saveAsTable writes the managed Delta tables there.
Run this PySpark cell once. mode("errorifexists") protects existing tables, and the preflight checks both names before either write. If a partial write fails, inspect the two lab objects before retrying; do not replace them blindly.
orders_name = "dbo.spark_join_lab_orders"
customers_name = "dbo.spark_join_lab_customers"
assert not spark.catalog.tableExists(orders_name), f"Already exists: {orders_name}"
assert not spark.catalog.tableExists(customers_name), f"Already exists: {customers_name}"
orders_source = spark.range(200_000).select(
F.col("id").alias("order_id"),
(F.col("id") % 1000).alias("customer_id"),
((F.col("id") % 100) + 1).cast("long").alias("amount"),
)
customers_source = spark.range(1000).select(
F.col("id").alias("customer_id"),
(F.col("id") % 5).cast("int").alias("segment"),
)
orders_source.write.format("delta").mode("errorifexists").saveAsTable(orders_name)
join_lab_created_tables.append(orders_name)
customers_source.write.format("delta").mode("errorifexists").saveAsTable(customers_name)
join_lab_created_tables.append(customers_name)
for name in [orders_name, customers_name]:
spark.table(name).agg(
F.count("*").alias("rows"),
F.countDistinct("customer_id").alias("distinct_customers"),
).show()
Derived baseline: orders has 200,000 rows and 1,000 distinct customers; customers has 1,000 rows and 1,000 distinct customers. Every order has exactly one matching customer. The amounts cycle through 1 to 100, so their total is 10,100,000.
3. Compare four equality-join plans
The following PySpark cell executes the same grouped answer with default planning and three hints. Each result contains five rows, so collecting it does not bring all orders to the driver.
These are four runs, not four distinct join algorithms. If both default and broadcast show BroadcastHashJoin in their final plans, that is an expected outcome: Spark chose broadcast without needing the hint.
collect() executes the same DataFrame whose plan is printed afterward. This avoids a common mistake: running df.count() and assuming it executed precisely the projected df plan. Count can prune columns or otherwise change the query.
from datetime import datetime, timezone
expected = [
(segment, 40_000, 1_940_000 + segment * 40_000)
for segment in range(5)
]
join_queries = {}
for label, hint in [
("default", ""),
("broadcast", "/*+ BROADCAST(c) */"),
("merge", "/*+ MERGE(o, c) */"),
("shuffle_hash", "/*+ SHUFFLE_HASH(c) */"),
]:
query = spark.sql(f"""
SELECT {hint} c.segment, COUNT(*) AS order_count,
SUM(o.amount) AS total_amount
FROM {orders_name} AS o
JOIN {customers_name} AS c ON o.customer_id = c.customer_id
GROUP BY c.segment
""")
join_queries[label] = query
print("BEFORE EXECUTION:", label, datetime.now(timezone.utc).isoformat())
query.explain(mode="cost")
actual = sorted(
(row.segment, row.order_count, row.total_amount)
for row in query.collect()
)
assert actual == expected, (label, actual)
print("AFTER EXECUTION:", label, datetime.now(timezone.utc).isoformat(), actual)
query.explain(mode="formatted")
Expected answer for every variant:
| Segment | Order count | Total amount |
|---|---|---|
| 0 | 40,000 | 1,940,000 |
| 1 | 40,000 | 1,980,000 |
| 2 | 40,000 | 2,020,000 |
| 3 | 40,000 | 2,060,000 |
| 4 | 40,000 | 2,100,000 |
Where the totals come from: because customer_id = order_id % 1000 and 1000 is divisible by 5, an order’s segment is also order_id % 5. In each 100-order cycle, segment 0 receives amounts 1, 6, ..., 96: 20 values summing to 970. There are 2,000 cycles, giving 40,000 orders and 970 * 2000 = 1,940,000. Each successive segment adds 1 to each of its 40,000 amounts, explaining the extra 40,000 in the formula. All five totals sum to the original 10,100,000.
In the completed plans, look for BroadcastHashJoin in the broadcast run, SortMergeJoin in merge, and ShuffledHashJoin in shuffle_hash. Record the operator that actually ran, even if it differs from the hint.
Read one plan from the leaves upward. This illustrative sort-merge tree includes the lab’s grouping; wrappers and projections are omitted:
HashAggregate(keys=[segment], functions=[count, sum])
+- Exchange hashpartitioning(segment, 8) [A]
+- HashAggregate(keys=[segment], functions=[partial_count, partial_sum])
+- SortMergeJoin [customer_id], [customer_id], Inner
:- Sort [customer_id ASC NULLS FIRST]
: +- Exchange hashpartitioning(customer_id, 8) [B]
: +- Scan orders
+- Sort [customer_id ASC NULLS FIRST]
+- Exchange hashpartitioning(customer_id, 8) [C]
+- Scan customers
| What you see | How to read it |
|---|---|
:-, +-, and indentation |
Parent/child relationships, not a serial execution timeline. Start at the scans and follow their output toward the root. |
[B] and [C]: hashpartitioning(customer_id, 8) |
Join shuffles route matching customer keys into corresponding execution partitions. Eight means target partitions for each exchange, not eight executors. AQE can change the number read downstream. |
Sort followed by SortMergeJoin |
Each input is ordered within its partition, then matching keys are merged. The join’s two key lists describe the left and right child keys; sort-merge has no hash-build side. |
Partial and final HashAggregate |
Tasks first calculate local counts/sums; the final aggregation combines those partial results. The word Hash here does not mean a hash join. |
[A]: hashpartitioning(segment, 8) |
This is the grouping shuffle, not a join shuffle. Segment groups must meet to produce the final five rows. It can remain even when broadcast removes the need to shuffle orders for the join. |
In the broadcast variant, BuildRight means the join node’s right child supplies the hash build, customers in that drawing. Inspect the children rather than guessing from SQL text: optimization can change their order. Formatted output may separate the tree from numbered node details; adaptive plans add stage/read wrappers.
Find the evidence in Fabric:
- In the notebook cell’s Spark job progress indicator, open More action, then Spark web UI. For an ended session, use Monitor, select its Spark application, and open Spark history server instead. These entry points are documented in Fabric’s Spark UI guide.
- Open the SQL tab (it may be labeled SQL / DataFrame) and select the completed execution for the grouped query. Match its query details and start time to the printed variant label’s UTC start/end timestamps, accounting for the UI’s displayed time zone. The four variants can share the same notebook call-site description, so a description alone is not a unique identifier.
- Save the adaptive plan’s Final Plan and Initial Plan where shown, including the final operator and its children.
- Inspect the join and exchange nodes for available row counts, broadcast size/time, shuffle bytes, and spill. Follow the execution’s associated job links to its Stages details for task-size and duration distributions. Save execution, job, and stage IDs so the evidence can be traced back to the variant; an operator node ID or whole-stage code-generation ID is not a Spark stage ID. See Spark’s SQL UI documentation.
A missing plan view or metric is unavailable evidence, not zero or proof of a conversion.
Grouped totals are useful but do not prove row-level equality on arbitrary data. For an optional duplicate-preserving full-output comparison, run this PySpark cell before cleanup:
def joined_rows(hint):
return spark.sql(f"""
SELECT {hint} o.order_id, o.customer_id, o.amount, c.segment
FROM {orders_name} AS o
JOIN {customers_name} AS c ON o.customer_id = c.customer_id
""")
reference = joined_rows("")
for hint in [
"/*+ BROADCAST(c) */",
"/*+ MERGE(o, c) */",
"/*+ SHUFFLE_HASH(c) */",
]:
candidate = joined_rows(hint)
assert reference.exceptAll(candidate).limit(1).count() == 0, hint
assert candidate.exceptAll(reference).limit(1).count() == 0, hint
These comparisons are separate executions, not a substitute for capturing the plans of the grouped queries above.
4. See a range join and a bounded cross join
Run these Spark SQL cells, each with %%sql as its first line. The first creates a session-local temporary view, not a stored table. Run it once: if that view name already exists, creation fails rather than replacing it. If you already created the view with this cell, rerun just the query below it; if the existing view is unfamiliar, stop rather than using or dropping it.
%%sql
CREATE TEMP VIEW spark_join_lab_bands AS
SELECT * FROM VALUES
('low', 1L, 26L),
('medium', 26L, 51L),
('high', 51L, 76L),
('premium', 76L, 101L)
AS bands(band, lower_bound, upper_bound);
%%sql
SELECT /*+ BROADCAST(b) */ b.band, COUNT(*) AS order_count
FROM dbo.spark_join_lab_orders AS o
JOIN spark_join_lab_bands AS b
ON o.amount >= b.lower_bound AND o.amount < b.upper_bound
GROUP BY b.band;
Expect four rows, 50,000 orders per band, in unspecified order. Inspect the completed execution for broadcast nested loop. The disjoint half-open ranges cover every lab amount exactly once.
%%sql
SELECT /*+ SHUFFLE_REPLICATE_NL(a) */ a.day_id, b.channel
FROM (SELECT * FROM VALUES (1), (2), (3) AS days(day_id)) AS a
CROSS JOIN (SELECT * FROM VALUES ('web'), ('store') AS channels(channel)) AS b;
Expect six rows: three days times two channels. Inspect for CartesianProduct; if the optimizer transforms this tiny constant query, record that fact rather than escalating to a large all-pairs test. The purpose is to understand a bounded Cartesian result, not manufacture an expensive plan.
5. Interpret the experiment honestly
| Observation | Interpretation and next step |
|---|---|
| All equality variants return the expected five rows | The grouped checks passed; save full-output comparisons if you ran them |
| A hint does not yield the expected operator | Check join eligibility, aliases, warnings, native execution, and the final rather than initial plan |
| Little or no shuffle at the join | Check the final join and its input exchanges. A broadcast join can avoid a join-key shuffle; a shuffled join can reuse compatible partitioning. Count the later grouping shuffle separately. |
| Similar elapsed times across variants | Startup and scheduling can mask differences on tiny inputs. Do not rank strategies by these timings; compare representative workloads instead. |
| Broadcast fails | Inspect driver/executor memory and actual build size; remove the hint before raising limits |
| Shuffled hash fails on representative data | Inspect the largest build partition and concurrent memory pressure; compare sort-merge |
| One task is much slower | Check partition sizes, key frequency, spill, GC, remote I/O, and output multiplication; duration alone does not prove skew |
| Initial and final plans differ | Save both and identify what AQE changed and which stages had already run |
Do not deliberately cause an out-of-memory failure in a shared capacity. This small, uniform lab does not validate production skew handling, broadcast memory limits, or AQE conversion thresholds.
For a real comparison, use the same source snapshots, query result, runtime/native mode, capacity, executor configuration, concurrency, and cache conditions. Separate cold and warm runs, repeat trials, and record bytes, spills, task tails, and elapsed time. Include input preparation costs when comparing layouts. Never extrapolate this lab’s timings to a multi-terabyte workload.
6. Clean up after saving diagnostics
Run this PySpark cell in the same session and default lakehouse, without renaming or replacing the tables between creation and cleanup. Setup preserves the list across cell reruns, and each write adds its name only after it succeeds. If the first preflight stops on an existing table, the list is empty: cleanup restores settings without dropping any table. If only the orders write succeeds, only orders is eligible for removal. Dropping a managed Delta table can remove its data.
try:
while join_lab_created_tables:
name = join_lab_created_tables[-1]
spark.sql(f"DROP TABLE IF EXISTS {name}")
join_lab_created_tables.pop()
finally:
for key, value in original_settings.items():
spark.conf.set(key, value)
End the disposable session to release its temporary price-band view. If the session is lost, or a write is interrupted before its name is recorded, do not reconstruct the list from the two table names. Verify ownership in the original lakehouse before removing anything manually. Ending a session discards its settings and temporary views, not its managed tables.
A practical operating checklist
- Preserve the required logical answer: join type, nulls, range endpoints, and duplicate behavior.
- Filter rows and project columns before expensive movement where semantics allow; inspect whether the optimizer already did so.
- Read the estimated plan, then the executed plan. Identify the join, build side, and actual exchanges.
- Size broadcasts using execution evidence and concurrency, not a fixed compressed-file cutoff.
- For shuffled hash, inspect the worst build partition; for sort-merge, inspect sort/shuffle spills and task tails.
- Keep AQE enabled unless a controlled investigation establishes a reason not to; do not assume it eliminates already completed work.
- Investigate hot keys before trying salting. Salting requires correctly replicating the other side and preserving outer/semi/anti semantics; a random extra key alone loses matches.
What you should be able to explain now
Whether you started directly with Spark or arrived from SQL Server, you now have the same model: the logical join defines the answer; the physical strategy determines how matches are found, where that happens, and how the records get there. SQL Server comparisons are a useful bridge, not a prerequisite.
You should now be able to distinguish a broadcast from a shuffle, explain why the same equality join can use three different algorithms, recognize why a pure range predicate is different, and inspect an executed plan rather than trusting a hint.
The successful Fabric Runtime 2.0 run establishes functional validation; production confidence requires representative measurements under the conditions described above.
The next step is not to force every join to broadcast. Take one important query, record its build input and movement costs, validate the answer, and compare one justified alternative. That is a stronger foundation for production confidence than memorizing a table-size threshold.
Further reading
- Microsoft: joins in SQL Server - Nested Loops, Merge, Hash, spill processing, and batch-mode Adaptive Join.
- Spark 4.1 SQL performance tuning - Statistics, strategy hints, automatic broadcast, AQE, and storage-partitioned joins.
- Spark 4.1 join-selection implementation - The version-pinned authority for strategy eligibility and fallback choices.
- Spark 4.1 SQL UI - How executed SQL plans and operator metrics relate to jobs and stages.
- Fabric Runtime 2.0 and Native Execution Engine - The managed lab’s component versions, setup, and alternate execution path.
Note: This blog post was written with assistance from AI