What you will be able to do
- Choose between inner, left, right, full, semi, anti and cross joins based on which unmatched rows must survive
- Write single-key and multi-key joins with join() and SQL USING, and predict which key columns appear in the output
- Use broadcast() to stop Spark from shuffling the large side of a join against a small lookup table
- Stack DataFrames with union() and unionByName(), and tell SQL UNION apart from UNION ALL
Key concept
Join type decides which unmatched rows survive — Every join matches rows on a key. The join type only decides what happens to rows that find no partner: inner drops them, outer joins keep them and fill the missing side with NULL, and semi or anti joins use the match as a filter.
1.Join types and what happens to unmatched rows
Joining puts columns from two DataFrames side by side wherever their keys match. Building a silver orders table that carries customer names, or a fact table that carries store regions, is a join. In PySpark the call is df.join(other, on, how). other is the right side, on says how rows match, and how names the join type. If you leave how out, you get an inner join.
The join type matters for rows whose key has no partner on the other side. An inner join returns only the rows whose key exists on both sides, so an order with an unknown customer_id disappears. A left join keeps every row of the left DataFrame and fills the right-hand columns with NULL when nothing matches. A right join does the same with the sides swapped, and a full outer join keeps unmatched rows from both sides.
Semi and anti joins filter rows instead of combining them. A left semi join returns left rows that have a match, but only the left columns: no right-hand values are added and unmatched rows are dropped. A left anti join returns the opposite set, the left rows with no match. Anti is the natural way to find, for example, transactions whose store_id is missing from stores. A cross join ignores keys entirely and pairs every left row with every right row.
> 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| Join type (how=) | Rows returned | Unmatched employees (deptno 4, 5, 6) | Columns |
|---|---|---|---|
| inner | 3 | Dropped | Both sides |
| left | 6 | Kept, deptname NULL | Both sides |
| right | 3 | Dropped (every department has a match) | Both sides |
| full | 6 | Kept, deptname NULL | Both sides |
| left_semi | 3 | Dropped | Left side only |
| left_anti | 3 | Only these are returned | Left side only |
Checkpoint 1 of 9· Fill the gap
This query returned all six employees, with NULL in deptname for departments 4, 5 and 6, which do not exist. Which join type fills the blank?
> SELECT id, name, employee.deptno, deptname
FROM employee
? 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 NULLOnly a left join keeps every left-side employee and puts NULL in the right-hand columns when there is no match. INNER and RIGHT would drop employees 104, 105 and 106. SEMI would drop them too and would not return deptname at all.
Source: docs.databricks.comCheckpoint 2 of 9· Match them up
You join transactions (left) to stores (right) on store_id. Match each join type to the result it gives.
Tap a term, then the definition that fits it.
Inner and left joins combine columns and differ only in whether unmatched left rows survive. Semi and anti joins filter the left rows by whether a match exists and add no right-hand columns.
“[ LEFT ] ANTI Returns the values from the left table reference that have no match with the right table reference.”Source: docs.databricks.com
Checkpoint 3 of 9· Exam question
A data engineer has a orders DataFrame and a customers DataFrame and wants to keep only the rows where the customer_id value exists in both DataFrames. Which join type produces this result?
Correct answer: A — Perform an inner join on customer_id, which returns only rows where the key matches in both DataFrames
- A. An inner join returns only the rows whose join key is present in both DataFrames, discarding unmatched rows on either side, which is exactly the requirement here.
- B. A left join keeps every row from
ordersregardless of whether a match exists incustomers, filling unmatched columns with null instead of discarding rows without a match. - C. A cross join produces the cartesian product of both DataFrames and ignores the join key entirely, so it does not filter to matching
customer_idvalues. - D. A right join keeps every row from
customersregardless of whether it matchesorders, which includes unmatched customer rows the requirement wants excluded.
Checkpoint 4 of 9· Exam question
A pipeline joins a transactions DataFrame to a stores DataFrame so that every transaction is retained in the output even when the corresponding store_id is missing from stores. Which join accomplishes this while preserving all transaction rows?
Correct answer: A — A left join with transactions as the left side, which fills stores columns with null for unmatched store_id values
- A. A left join keeps every row from the left DataFrame and populates columns from the right DataFrame with null when no match is found, satisfying the requirement to retain all transactions.
- B. An inner join removes rows whose key has no counterpart on the other side, so transactions with a missing store would be dropped rather than preserved.
- C. A cross join ignores the join key and multiplies rows by pairing every transaction with every store, which does not preserve one row per original transaction.
- D. A left semi join keeps only left-side columns for rows that have a match and drops rows without one, so it does not retain transactions that lack a matching store.
2.Join keys: column names, expressions and multiple keys
The on argument takes four shapes: a column name, a list of column names, a Column expression, or a list of Columns. The choice affects the output schema. If you pass a name or a list of names, that column must exist on both sides and Spark runs an equi-join. The output then has the key only once. If you pass an expression such as df.name == df2.name, both key columns stay in the result, so a later select("name") is ambiguous.
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, "name").show()
# +----+---+------+
# |name|age|height|
# +----+---+------+
# | Bob| 5| 85|
# +----+---+------+
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|
# +-----+----+----+------+Use a multi-key join when one column does not identify a row, for example sales keyed by both store_id and sale_date. In PySpark, pass a list such as on=["store_id", "sale_date"]. In SQL, USING (a, b) does the same thing. SELECT * FROM first JOIN second USING (a, b) is equivalent to an ON first.a = second.a AND first.b = second.b join, and it shows each key column once, before the remaining left and right columns. A key named in USING that is missing from one side raises UNRESOLVED_USING_COLUMN_FOR_JOIN.
A self-join needs aliases because both sides have identical column names. df.alias("a").join(df.alias("b"), sf.col("a.name") == sf.col("b.name"), "outer") lets you refer to either side's column without ambiguity.
One. When on is a list of names, Spark runs an equi-join on columns that exist on both sides, and each join column appears once. You would get two only by joining on a Column expression.
Checkpoint 5 of 9· Check yourself
You need to combine daily_sales with daily_targets. A row is identified by store_id and sale_date together. Only matched rows should be kept, the target columns must be included, and SELECT * should show store_id and sale_date once each. Which FROM clause does this?
USING with both keys matches rows on store_id and sale_date, and SELECT * shows each key column once. The ON version matches the same rows but keeps both copies of each key. USING (store_id) alone matches every date's target for a store. A SEMI join adds no target columns.
“When you specify USING or NATURAL, SELECT * will only show one occurrence for each of the columns used to match first”Source: docs.databricks.com
3.Cross joins and the Cartesian product
A cross join pairs every row on the left with every row on the right, so the output row count is the product of the two input counts. It is the right tool when you need every combination, such as every store against every day of a calendar to build a grid you can fill in later. In PySpark it is df.crossJoin(other) or join(other, how="cross"), and in SQL it is CROSS JOIN.
from pyspark.sql import Row
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.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|
# +---+-----+------+You can also get a cross join by accident. In SQL, if you write a join without an ON or USING clause, any join type behaves like a CROSS JOIN. A forgotten condition between a million-row table and a thousand-row table produces a billion rows. That is why Databricks calls cross joins expensive and advises removing them from queries that need low latency or frequent recomputation. A cross join never speeds up an ordinary keyed join: it does more work, not less.
Join order is the other cost lever when a query chains several joins. Join the smallest tables first, then join that result to the larger ones.
Checkpoint 6 of 9· Check yourself
A nightly job runs SELECT * FROM orders LEFT JOIN regions. orders has 1,000,000 rows and regions has 1,000 rows. The author forgot the ON clause. What does Databricks SQL return?
With no ON or USING clause, every join type becomes a CROSS JOIN, so the result is the Cartesian product: 1,000,000 × 1,000 rows. The LEFT keyword does not limit the result to one row per order, and Spark does not match on shared column names unless you write NATURAL.
“If you omit the join_criteria the semantic of any join_type becomes that of a CROSS JOIN.”Source: docs.databricks.com
4.Broadcast joins for a large table and a small one
In a standard distributed join, both DataFrames are shuffled across the cluster so that rows with the same key end up on the same machine. When one side is 500 GB of events and the other is a 40 MB lookup table, almost all of that network traffic comes from moving the large side. A broadcast join avoids this: Spark sends a full copy of the small table to every worker node. Each partition of the large table is then joined where it already sits, and the large side is not shuffled.
broadcast() from pyspark.sql.functions marks a DataFrame as small enough for a broadcast join. You wrap the small side, not the large one, and pass it to an ordinary join. The SQL equivalent is the /*+ BROADCAST(t1) */ hint, with BROADCASTJOIN and MAPJOIN as aliases.
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()Spark also broadcasts automatically when a table is under spark.sql.autoBroadcastJoinThreshold, which defaults to 10 MB in Apache Spark. At 40 MB the lookup table is over that limit, so without a hint the join can fall back to shuffling both sides. An explicit hint removes the guesswork, because the side with the hint is broadcast regardless of the threshold. Changing the threshold itself, and the runtime re-planning that can switch join strategies, belong to Spark tuning parameters.
Checkpoint 7 of 9· Fill the gap
In this sample, df is the side that should stay where it is and df_small is the lookup table. Which DataFrame belongs in the blank so that Spark copies only the small table to every worker and does not shuffle the large one?
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 a DataFrame as small enough to send a full copy to every worker, so you wrap the small lookup side. The large side is then joined where its partitions already sit, without a shuffle. Wrapping df would copy the large table everywhere, and a union is not a join input you would broadcast.
Source: docs.databricks.comCheckpoint 8 of 9· Exam question
A join between a 500 GB events DataFrame and a 40 MB lookup_codes DataFrame is running slowly because Spark shuffles both sides across the cluster. Which change is most likely to speed up this join?
Correct answer: A — Wrap lookup_codes with broadcast() so Spark copies it to every executor and avoids shuffling the join
- A. Broadcasting the small DataFrame copies it to every executor so the large side can be joined locally without a shuffle, which is the standard fix for a large-to-small join that is running slowly.
- B. Forcing
eventsinto a single partition removes parallelism and makes one executor process the entire 500 GB DataFrame, which would make the join slower, not faster. - C. A cross join computes the cartesian product of both DataFrames rather than matching on a key, which changes the query's meaning and does not eliminate the need to distribute data across the cluster.
- D. Caching the large DataFrame keeps it in memory for reuse across actions but does not avoid the shuffle exchange caused by joining two large partitioned datasets.
5.Stacking rows: union, unionByName, UNION and UNION ALL
A union adds one DataFrame's rows below another's, where a join adds columns side by side. You union when monthly extracts, regional feeds or a backfill share a schema and need to become one table. In PySpark, union() lines up columns by position: the first column of other goes under the first column of self, whatever the names are. It also does not remove duplicates, so it keeps every row, like SQL UNION ALL. If you need distinct rows, follow it with distinct(); general row deduplication is covered in deduplication operations.
df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"])
df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col0"])
df1.unionByName(df2).show()
# +----+----+----+
# |col0|col1|col2|
# +----+----+----+
# | 1| 2| 3|
# | 6| 4| 5|
# +----+----+----+Positional matching fails silently, so it is the riskier choice. If one source writes (id, amount, fee) and another writes (id, fee, amount), union() still succeeds and puts fees in the amount column as long as the types are compatible. unionByName() avoids this. With allowMissingColumns=True it can also stack inputs whose column sets differ, such as a feed that added a column last quarter. Columns missing from one input are filled with NULL, and the result contains every column from both.
SQL works the other way round from the DataFrame API. A plain UNION means UNION DISTINCT and removes duplicate rows. UNION ALL keeps them. Both sides must have the same number of columns, or Databricks raises NUM_COLUMNS_MISMATCH. Each result column takes the least common type of the two inputs.
| Operation | Matches columns by | Duplicates | Rows from the example |
|---|---|---|---|
| SQL UNION (same as UNION DISTINCT) | Position | Removed | 5 (1, 3, 5, 4, 2) |
| SQL UNION ALL | Position | Kept | 10 |
| DataFrame union() | Position | Kept | 10 |
| DataFrame unionByName() | Name | Kept | 10 |
Checkpoint 9 of 9· Fill the gap
df1 and df2 both contain the row (3, 'C'). The combined output below should list that row only once. Which method belongs in the blank?
df1 = spark.createDataFrame([(1, 'A'), (2, 'B'), (3, 'C')], ['id', 'value'])
df2 = spark.createDataFrame([(3, 'C'), (4, 'D')], ['id', 'value'])
df3 = df1.union(df2). ? ().sort("id")
df3.show()
# +---+-----+
# | id|value|
# +---+-----+
# | 1| A|
# | 2| B|
# | 3| C|
# | 4| D|
# +---+-----+DataFrame union() keeps duplicates, as SQL UNION ALL does. Without another step, (3, 'C') would appear twice. Adding distinct() removes the duplicate. unionByName changes how columns are matched, not whether duplicates are kept, and unionAll would still keep both copies.
Source: docs.databricks.comPractise it for real
In a notebook, compare union(), union().distinct() and unionByName(allowMissingColumns=True) on small DataFrames.
1.Create df1 = spark.createDataFrame([(1, 'A'), (2, 'B'), (3, 'C')], ['id', 'value']) and df2 = spark.createDataFrame([(3, 'C'), (4, 'D')], ['id', 'value']), then run df1.union(df2).show().
Why: This shows that union() keeps every row from both inputs.
You should see: Five rows, with (3, C) appearing twice.
2.Run df1.union(df2).distinct().sort("id").show().
Why: union() never deduplicates, so removing duplicates needs an explicit distinct().
You should see: Four rows: ids 1, 2, 3 and 4, each once.
3.Create df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"]) and df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col3"]), then run df1.unionByName(df2, allowMissingColumns=True).show().
Why: This shows name-based matching across inputs whose column sets differ.
You should see: Four columns, col0 to col3. The first row has NULL in col3 and the second row has NULL in col0.
Stuck? Get a nudge
Run step 3 again without allowMissingColumns=True and compare the result with the default behaviour.
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Returns the rows that have matching values in both table references.”
↩︎ Join types and what happens to unmatched rows“appends NULL if there is no match”
↩︎ Join types and what happens to unmatched rows“Returns the values from the left table reference that have no match with the right table reference.”
↩︎ Join types and what happens to unmatched rows“SELECT * will only show one occurrence for each of the columns used to match first”
↩︎ Join keys: column names, expressions and multiple keys“If a column is not found in one of the relations, Databricks raises UNRESOLVED_USING_COLUMN_FOR_JOIN.”
↩︎ Join keys: column names, expressions and multiple keys“Returns all values from both relations, appending NULL values on the side that does not have a match.”
↩︎ Key concept“Returns values from the left side of the table reference that has a match with the right.”
↩︎ Exam trap 1“If you omit the join_criteria the semantic of any join_type becomes that of a CROSS JOIN.”
↩︎ Exam trap 2“[ LEFT ] ANTI Returns the values from the left table reference that have no match with the right table reference.”
↩︎ Checkpoint“When you specify USING or NATURAL, SELECT * will only show one occurrence for each of the columns used to match first”
↩︎ Checkpoint“Returns the Cartesian product of two relations.”
↩︎ Prediction“If you omit the join_criteria the semantic of any join_type becomes that of a CROSS JOIN.”
↩︎ Checkpoint - 2.
“default inner”
↩︎ Join types and what happens to unmatched rows“the column(s) must exist on both sides, and this performs an equi-join.”
↩︎ Join keys: column names, expressions and multiple keys - 3.
“Returns the cartesian product with another DataFrame.”
↩︎ Cross joins and the Cartesian product - 4.
“Cross joins are expensive. Remove cross joins from workloads and queries that require low latency or frequent recomputation.”
↩︎ Cross joins and the Cartesian product“When performing multiple joins, always join your smallest tables first and then join the result with larger tables.”
↩︎ Cross joins and the Cartesian product - 5.
“Marks a DataFrame as small enough for use in broadcast joins.”
↩︎ Broadcast joins for a large table and a small one - 6.
“It chose a broadcast join instead of shuffling data across the cluster”
↩︎ Broadcast joins for a large table and a small one - 7.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 joins for a large table and a small one“spark.sql.autoBroadcastJoinThreshold | 10485760 (10 MB)”
↩︎ Broadcast joins for a large table and a small one - 8.
“BROADCASTJOIN and MAPJOIN are supported as aliases for BROADCAST.”
↩︎ Broadcast joins for a large table and a small one“The join side with the hint is broadcast regardless of autoBroadcastJoinThreshold.”
↩︎ Exam trap 3 - 9.
“This method performs a SQL-style set union of the rows from both DataFrame objects, with no automatic deduplication of elements.”
↩︎ Stacking rows: union, unionByName, UNION and UNION ALL“The method resolves columns by position (not by name), following the standard behavior in SQL.”
↩︎ Exam trap 4 - 10.
“When allowMissingColumns is True, missing columns will be filled with null.”
↩︎ Stacking rows: union, unionByName, UNION and UNION ALL“resolving columns by name (rather than position)”
↩︎ Prediction - 11.https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-select-setopsOfficial docs
“If DISTINCT is specified the result does not contain any duplicate rows. This is the default.”
↩︎ Stacking rows: union, unionByName, UNION and UNION ALL“If the number of columns differs, Databricks raises NUM_COLUMNS_MISMATCH.”
↩︎ Stacking rows: union, unionByName, UNION and UNION ALL“The type of each result column is the least common type of the respective columns in subquery1 and subquery2.”
↩︎ Stacking rows: union, unionByName, UNION and UNION ALL