What you will be able to do
- Predict which rows an inner, left or cross join keeps, including rows with null or unmatched keys
- Join on one or several keys without duplicate key columns by passing column names to on
- Force a broadcast join with broadcast() on the small DataFrame and explain when Spark broadcasts on its own
- Choose between union and unionByName, and remove duplicates when set semantics are needed
Key concept
Join contract: on + how — DataFrame.join(other, on, how) combines two DataFrames side by side. on says which rows match: column names or a Column expression. how says what happens to rows with no match: they are dropped (inner), kept with NULLs (left), or every row is paired with every other row (cross).
1.Inner join: only rows that match on both sides
A join puts two DataFrames side by side. A union stacks one on top of the other. Most pipelines need both. Joins enrich facts with lookups, such as orders with customers or transactions with country codes. Unions merge batches that share a shape. All the join types use the same call, df.join(other, on, how). other is the right side. on names the matching column(s) or gives a join expression. how defaults to inner.
An inner join keeps a row only if its key finds a partner on the other side. Unmatched rows are dropped from both sides, so the result never contains a NULL-padded row. Picture an employees table where one person's dept_id is null, joined to a departments table that has a department nobody works in. The null key equals no department key, so that employee disappears. The empty department also disappears, because no employee points to it. If two of three employees match, the result has two rows. It never has three, and it never has a row with a NULL dept_name.
Passing the key as a string, on="dept_id", also changes the output shape. The column must exist in both DataFrames, and Spark performs an equi-join that keeps one copy of the key. In the example below, name is in both inputs but appears once in the result. Only Bob is in both inputs, so only Bob comes out. Alice and Tom each lack a partner.
df.join(df2, "name").show()
# +----+---+------+
# |name|age|height|
# +----+---+------+
# | Bob| 5| 85|
# +----+---+------+Checkpoint 1 of 9· Fill the gap
This inner join returns one name column and only the row whose key appears in both DataFrames. Which on argument completes it?
df = spark.createDataFrame([Row(name="Alice", age=2), Row(name="Bob", age=5)])
df2 = spark.createDataFrame([Row(name="Tom", height=80), Row(name="Bob", height=85)])
df.join(df2, ? ).show()
# +----+---+------+
# |name|age|height|
# +----+---+------+
# | Bob| 5| 85|
# +----+---+------+When on is a string, that column must exist in both DataFrames. Only name does. Spark then does an equi-join that keeps one copy of the key. Because how defaults to inner, Alice and Tom have no partner and are dropped, so only Bob is returned.
Checkpoint 2 of 9· Exam question
employees = spark.createDataFrame(
[(1, "Ana", 10), (2, "Ben", 20), (3, "Cara", None)],
["emp_id", "name", "dept_id"]
)
departments = spark.createDataFrame(
[(10, "Sales"), (20, "Engineering"), (30, "Marketing")],
["dept_id", "dept_name"]
)
result = employees.join(departments, on="dept_id", how="inner")
How many rows does result contain, and why?
Correct answer: B — Two rows, because Cara's null dept_id matches nothing in departments, and the unmatched Marketing row is dropped too.
- A. This describes left-join behavior, not inner-join behavior. An inner join only keeps rows where the join key is present on both sides, so a null
dept_idand an unmatched department row are both excluded. - B. This is correct. Cara's
dept_idis null, and null never satisfies an equality join condition, so her row is dropped; Marketing has no matching employee, so it is dropped too, leaving only Ana-Sales and Ben-Engineering. - C. Inner joins never keep an unmatched left row with nulls filled in for the right side — that padding behavior is specific to outer joins, not inner joins.
- D. Marketing would only survive the join if some employee row had
dept_id = 30, which none do; an inner join drops departments with no matching employees. - E. A cartesian-style multiplication of unmatched keys against every row on the other side only happens in a cross join, not an equality-based inner join.
2.Left join: keep every row from the left
A left join keeps every row of the left DataFrame and fills the right side's columns with NULL where no match exists. Choose it when the left table is the thing you are reporting on. A list of all employees with their department name, where some names are unknown, is a left join. An inner join would quietly drop those employees, and a headcount built from it would be too low. Rows that exist only on the right still do not appear. Keeping those as well takes a full outer join. In PySpark, how="left", "leftouter" and "left_outer" all mean the same thing.
> SELECT id, name, employee.deptno, deptname
FROM employee
LEFT JOIN department ON employee.deptno = department.deptno;
105 Chloe 5 NULL
103 Paul 3 Engineering
101 John 1 Marketing
102 Lisa 2 Sales
104 Evan 4 NULL
106 Amy 6 NULL| how | Matched rows | Unmatched left rows | Unmatched right rows |
|---|---|---|---|
| inner (default) | Kept | Dropped | Dropped |
| left / leftouter / left_outer | Kept | Kept, right columns NULL | Dropped |
| right / rightouter / right_outer | Kept | Dropped | Kept, left columns NULL |
| outer / full / fullouter / full_outer | Kept | Kept, right columns NULL | Kept, left columns NULL |
Checkpoint 3 of 9· Check yourself
A report must list every employee exactly once with their department name. Employees whose deptno is missing from the departments lookup should still appear, and departments with no employees should not. Which call produces this?
A left join keeps every row from the left side (employees) and puts NULL in the right-side columns when there is no match. It does not add departments that have no employees. An inner join would drop the unmatched employees. A right join keeps departments instead of employees. A full outer join would also add rows for departments with no employees.
“Returns all values from the left table reference and the matched values from the right table reference, or appends NULL if there is no match.”Source: docs.databricks.com
3.Joining on multiple keys without duplicate columns
Some rows are only unique on a combination of columns, such as (store_id, sku) or (region, date). For these, pass a list of column names: on=["a", "b"]. Each name must exist on both sides, and a row matches only if every listed column is equal. The output has one copy of each key column, followed by the remaining left columns and then the remaining right columns. The SQL form USING (a, b) behaves the same way.
SELECT * FROM first JOIN second USING (a, b)
is equivalent to
SELECT first.a, first.b,
first.* EXCEPT(a, b),
second.* EXCEPT(a, b)
FROM first JOIN second ON first.a = second.a AND first.b = second.bA join expression, meaning a Column such as df.name == df2.name (or several conditions combined with &), keeps both copies of the key. In the outer join below, the result has two name columns. A later select("name") on that result is ambiguous. Use the expression form when the key columns have different names, or when the condition is not plain equality. Otherwise the list of names gives a cleaner result.
joined = df.join(df2, df.name == df2.name, "outer").sort(sf.desc(df.name))
joined.show()
# +-----+----+----+------+
# | name| age|name|height|
# +-----+----+----+------+
# | Bob| 5| Bob| 85|
# |Alice| 2|NULL| NULL|
# | NULL|NULL| Tom| 80|
# +-----+----+----+------+orders.join(stock, on=["store_id", "sku"]). Joining with orders.store_id == stock.store_id & orders.sku == stock.sku matches the same rows but keeps two copies of each key column.
Checkpoint 4 of 9· Check yourself
In orders, the customer key column is cust_id. In customers, the same key is stored in a column called id. Which join call matches each order to its customer?
When on is given as column names, each name must exist in both DataFrames. Neither cust_id nor id does, so all three name-based calls fail. When the key columns have different names, you need a join expression such as orders.cust_id == customers.id. The result keeps both key columns.
“the column(s) must exist on both sides, and this performs an equi-join”Source: docs.databricks.com
4.Cross join: every row with every row
A cross join pairs every left row with every right row. Three ages crossed with two heights gives six rows. With a million rows on each side, it gives a trillion. You can request it with df.crossJoin(other) or df.join(other, how="cross"). Use it when you need every combination, such as every product against every price tier. The output grows multiplicatively, so keep cross joins out of low-latency or frequently recomputed workloads.
df.crossJoin(df2.select("height")).select("age", "name", "height"
).orderBy("age", "name", "height").show()
# +---+-----+------+
# |age| name|height|
# +---+-----+------+
# | 14| Tom| 80|
# | 14| Tom| 85|
# | 16| Bob| 80|
# | 16| Bob| 85|
# | 23|Alice| 80|
# | 23|Alice| 85|
# +---+-----+------+An accidental cross join happens when the join condition is left out. In SQL, a JOIN with no ON or USING clause behaves as a CROSS JOIN, whatever join type you wrote. A job that ran in seconds on test data and runs for hours in production is often missing a join key.
Checkpoint 5 of 9· Fill the gap
No key is passed, and the result pairs each of the three people with both heights, giving six rows. Which method produces this output?
df = spark.createDataFrame(
[(14, "Tom"), (23, "Alice"), (16, "Bob")], ["age", "name"])
df2 = spark.createDataFrame(
[Row(height=80, name="Tom"), Row(height=85, name="Bob")])
df. ? (df2.select("height")).select("age", "name", "height"
).orderBy("age", "name", "height").show()
# +---+-----+------+
# |age| name|height|
# +---+-----+------+
# | 14| Tom| 80|
# | 14| Tom| 85|
# | 16| Bob| 80|
# | 16| Bob| 85|
# | 23|Alice| 80|
# | 23|Alice| 85|
# +---+-----+------+crossJoin returns the Cartesian product, so every left row is paired with every right row: 3 × 2 = 6 rows, with no key needed. A union stacks rows instead of putting them side by side, so it could not produce rows that combine age, name and height.
Source: docs.databricks.com5.broadcast() as a join option
In a Broadcast hash join, Spark ships a full copy of the small side to every executor so the large side does not have to shuffle. In DataFrame code, the broadcast is not a separate method. You wrap the small DataFrame in broadcast() from pyspark.sql.functions and pass the wrapped DataFrame to join as usual. broadcast(df) marks that DataFrame as small enough to broadcast.
from pyspark.sql import functions as dbf
df = spark.createDataFrame([1, 2, 3, 3, 4], "int")
df_small = spark.range(3)
df_b = dbf.broadcast(df_small)
df.join(df_b, df.value == df_small.id).show()Without any hint, Spark broadcasts automatically based on size. It estimates the size of each side in bytes and compares it with spark.sql.autoBroadcastJoinThreshold, which defaults to 10485760 bytes (10 MB). The decision depends on byte size from statistics. Row counts, the order of the DataFrames in the call, and whether broadcast was imported do not affect it, and neither does spark.sql.shuffle.partitions. Setting the threshold to -1 turns automatic broadcasting off completely.
The hint still works when the threshold is off. The DataFrame you wrap becomes the build side, meaning the side Spark broadcasts to every executor, and Spark prioritizes broadcasting it even if its estimated size is above the threshold. Suppose a cluster has the threshold set to -1 and you join a 500 GB transactions table to a 2 MB country_codes lookup. Writing transactions.join(broadcast(country_codes), on="country_id") restores the broadcast for that one join. Wrapping transactions instead would try to ship 500 GB to every executor. There is no country_codes.broadcast() method, because broadcast is a function, not a DataFrame method. repartition(1) changes partitioning and does not broadcast anything. The join algorithm that runs after the broadcast depends on the join condition. When the join has an equi-join key, meaning an equality condition on key columns, Spark runs a broadcast hash join. When it has no equi-join key, as in a cross join, Spark runs a broadcast nested loop join instead. The broadcast() hint is written the same way in both cases.
Checkpoint 6 of 9· Fill the gap
Here df is the larger side of the join and df_small is a three-row lookup. The goal is to copy the lookup to every executor so the larger side does not have to shuffle. Which DataFrame should be passed to dbf.broadcast?
from pyspark.sql import functions as dbf
df = spark.createDataFrame([1, 2, 3, 3, 4], "int")
df_small = spark.range(3)
df_b = dbf.broadcast( ? )
df.join(df_b, df.value == df_small.id).show()broadcast() marks the DataFrame it wraps as the one to copy to every executor, so it must wrap the small side. Here that is df_small. You then pass the wrapped result to join as usual. Its position in the call does not matter. Wrapping df would ship the larger table, and wrapping a finished join marks the wrong thing.
Checkpoint 7 of 9· Exam question
A developer runs df_small.join(df_large, "key") without any join hints, and Spark's optimizer automatically converts it into a broadcast hash join. Under the default configuration, what determines whether Spark performs this automatic conversion?
Correct answer: D — Spark estimates df_small's size and compares it against spark.sql.autoBroadcastJoinThreshold, which defaults to 10 MB.
- A.
spark.sql.shuffle.partitionscontrols how many partitions a shuffle produces after a wide transformation; it plays no role in deciding whether a table is small enough to broadcast. - B. Join order in the code has no bearing on which side gets broadcast — the optimizer picks based on estimated size, and either side could be chosen.
- C. Automatic broadcast selection is based on estimated data size in bytes, not row count, since a narrow table with millions of tiny rows could still be small while a wide table with a few rows could be large.
- D. This is correct. Spark's catalyst optimizer compares the estimated byte size of each side against
spark.sql.autoBroadcastJoinThreshold, whose default is 10485760 bytes (10 MB), and automatically broadcasts a side that falls under it. - E. Automatic broadcast conversion is a cost-based optimizer decision that happens regardless of whether
broadcast()has been imported; the import only matters for forcing a broadcast explicitly.
Checkpoint 8 of 9· Exam question
A pipeline joins a 500 GB transactions DataFrame with a 2 MB country_codes lookup DataFrame. spark.sql.autoBroadcastJoinThreshold has been set to -1 in the cluster's Spark config, disabling automatic broadcast selection, but the developer still wants this specific join to avoid a shuffle. Which line correctly forces country_codes to be broadcast?
from pyspark.sql.functions import broadcast
result = transactions.join(
____________,
on="country_id",
how="inner"
)
Correct answer: A — broadcast(country_codes)
- A. This is correct. Wrapping the small lookup DataFrame in
pyspark.sql.functions.broadcast()marks it for a broadcast hash join, which works even when the automatic threshold has been disabled. - B.
broadcastis a module-level function inpyspark.sql.functions, not a DataFrame method, so calling.broadcast()on a DataFrame instance raises anAttributeError. - C. Collapsing a DataFrame to one partition changes its parallelism but does not tell the join planner to skip the shuffle; the join would still execute as a shuffle-based join.
- D. Passing the string
"shuffle"to.hint()requests a sort-merge/shuffle join strategy, which is the opposite of what avoiding a shuffle requires here. - E. Broadcasting the 500 GB
transactionsDataFrame instead of the 2 MB lookup table would try to replicate a huge dataset to every executor, which is the wrong side to mark and would likely exhaust executor memory.
6.union, UNION ALL and unionByName
union stacks the rows of two DataFrames and keeps every row, including duplicates. That is the behaviour SQL calls UNION ALL. It does not deduplicate. If a row appears in both inputs, it appears twice in the output. To get set semantics, follow union with distinct().
df1 = spark.createDataFrame([(1, 'A'), (2, 'B'), (3, 'C')], ['id', 'value'])
df2 = spark.createDataFrame([(3, 'C'), (4, 'D')], ['id', 'value'])
df3 = df1.union(df2).distinct().sort("id")
df3.show()
# +---+-----+
# | id|value|
# +---+-----+
# | 1| A|
# | 2| B|
# | 3| C|
# | 4| D|
# +---+-----+union matches columns by position, and the column names of the second DataFrame are ignored. This causes a common silent bug. Two daily extracts have the same columns in different orders, and union puts one file's values under the other file's column names. When the types happen to be compatible, nothing fails and the data is simply wrong. unionByName matches columns by name. With allowMissingColumns=True, it also accepts inputs whose column sets differ and fills the missing columns with null.
df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"])
df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col3"])
df1.unionByName(df2, allowMissingColumns=True).show()
# +----+----+----+----+
# |col0|col1|col2|col3|
# +----+----+----+----+
# | 1| 2| 3|NULL|
# |NULL| 4| 5| 6|
# +----+----+----+----+| Method | Columns matched by | Different column sets | Duplicates |
|---|---|---|---|
| union(other) | Position | Not handled | Kept (UNION ALL behaviour) |
| unionByName(other) | Name | Not allowed (allowMissingColumns defaults to False) | Kept |
| unionByName(other, allowMissingColumns=True) | Name | Missing columns filled with null | Kept |
| union(other).distinct() | Position | Not handled | Removed |
Checkpoint 9 of 9· Match them up
Match each row-stacking call to how it lines up columns and what it does with duplicate rows.
Tap a term, then the definition that fits it.
union ignores the second DataFrame's column names and stacks by position. It keeps duplicates unless you add distinct(). unionByName matches columns by name, and it accepts inputs with different column sets only when allowMissingColumns=True, which fills the gaps with null.
“The method resolves columns by position (not by name), following the standard behavior in SQL.”Source: docs.databricks.com
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“the column(s) must exist on both sides, and this performs an equi-join”
↩︎ Inner join: only rows that match on both sides“default inner. Must be one of: inner, cross, outer, full, fullouter, full_outer, left, leftouter, left_outer,”
↩︎ Left join: keep every row from the left“a string for the join column name, a list of column names, a join expression (Column), or a list of Columns.”
↩︎ Joining on multiple keys without duplicate columns“the column(s) must exist on both sides, and this performs an equi-join”
↩︎ Key concept“the column(s) must exist on both sides, and this performs an equi-join”
↩︎ Checkpoint - 2.
“Returns the rows that have matching values in both table references.”
↩︎ Inner join: only rows that match on both sides“appends NULL if there is no match. It is also referred to as a left outer join.”
↩︎ Left join: keep every row from the left“SELECT * will only show one occurrence for each of the columns used to match first”
↩︎ Joining on multiple keys without duplicate columns“If you omit the join_criteria the semantic of any join_type becomes that of a CROSS JOIN.”
↩︎ Cross join: every row with every row“Returns the rows that have matching values in both table references.”
↩︎ Exam trap 1“SELECT * will only show one occurrence for each of the columns used to match first”
↩︎ Exam trap 4“Returns all values from the left table reference and the matched values from the right table reference, or appends NULL if there is no match.”
↩︎ Checkpoint - 3.
“Returns the cartesian product with another DataFrame.”
↩︎ Cross join: every row with every row - 4.
“Cross joins are expensive.”
↩︎ Cross join: every row with every row - 5.
“Marks a DataFrame as small enough for use in broadcast joins.”
↩︎ broadcast() as a join option - 6.https://spark.apache.org/docs/latest/sql-performance-tuning.htmlSecondary source
“Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join.”
↩︎ broadcast() as a join option“By setting this value to -1, broadcasting can be disabled.”
↩︎ broadcast() as a join option“broadcast join (either broadcast hash join or broadcast nested loop join depending on whether there is any equi-join key)”
↩︎ broadcast() as a join option“10485760 (10 MB)”
↩︎ broadcast() as a join option“Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join.”
↩︎ Exam trap 2 - 7.
“The join side with the hint is broadcast regardless of autoBroadcastJoinThreshold.”
↩︎ broadcast() as a join option - 8.
“with no automatic deduplication of elements.”
↩︎ union, UNION ALL and unionByName“resolves columns by position (not by name), following the standard behavior in SQL.”
↩︎ union, UNION ALL and unionByName“with no automatic deduplication of elements.”
↩︎ Exam trap 3“The method resolves columns by position (not by name), following the standard behavior in SQL.”
↩︎ Checkpoint - 9.
“resolving columns by name (rather than position). When allowMissingColumns is True, missing columns will be filled with null.”
↩︎ union, UNION ALL and unionByName