Sub topic 13
Joining DataFrames
This chapter assumes you can create a DataFrame, select and filter columns, and run a groupBy aggregation in a Databricks notebook. It covers how join works, which join types exist, and the errors that most often surprise people.
What a join does
A join combines rows from two DataFrames by matching values in one or more columns, called the join keys. Each row in the left DataFrame is compared with rows in the right DataFrame. The join type decides what happens to rows that match and rows that do not.
The examples use the orders DataFrame from earlier chapters and a small customers DataFrame.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
).withColumn("order_date", F.to_date("order_date"))
customers = spark.createDataFrame(
[("alice", "US"), ("bob", "DE")],
"customer STRING, country STRING",
)
enriched = orders.join(customers, on="customer", how="left")
display(enriched)Carol has no row in customers. Because this is a left join, her order stays in the result and country is null.
The signature is left.join(right, on=..., how=...). If you omit how, Spark uses inner.
Join types
| `how` value | Rows returned |
|---|---|
| `inner` | Only rows with a match on both sides |
| `left` (or `left_outer`) | All left rows, with nulls where the right has no match |
| `right` (or `right_outer`) | All right rows, with nulls where the left has no match |
| `full` (or `outer`) | All rows from both sides, with nulls where there is no match |
| `left_semi` | Left rows that have a match, with only left columns |
| `left_anti` | Left rows that have no match, with only left columns |
| `cross` | Every left row paired with every right row |
Semi and anti joins are filters, not combinations. They never add right-side columns and never duplicate left rows. Use left_anti to answer "which orders have no known customer?"
unknown_customers = orders.join(customers, on="customer", how="left_anti")
display(unknown_customers)This returns only order 4, with the original four orders columns.
known_orders = orders.join(customers, on="customer", how="left_semi")
display(known_orders)Choosing how to specify the keys
You can pass the keys in three ways. They differ in what the output columns look like.
- A column name or list of names:
on="customer"oron=["customer", "region"]. Both DataFrames must have columns with these names. The output contains onecustomercolumn. - A condition expression:
on=orders["customer"] == customers["customer"]. The output contains bothcustomercolumns. - A combined condition with
&:on=(a["x"] == b["x"]) & (a["d"] >= b["start"]). Use this for non-equality conditions.
cond = orders["customer"] == customers["customer"]
both = orders.join(customers, on=cond, how="inner")
both.printSchema()The schema shows two columns named customer. Selecting "customer" later raises an AMBIGUOUS_REFERENCE error, because Spark cannot tell which one you mean.
Avoiding duplicate column names
You have three options when the key names are the same on both sides.
- Use
on="customer"so Spark merges them into one column. - Drop one side after the join with
.drop(customers["customer"]). - Alias the DataFrames and refer to columns by alias.
o = orders.alias("o")
c = customers.alias("c")
result = (
o.join(c, F.col("o.customer") == F.col("c.customer"), "left")
.select("o.order_id", "o.customer", "c.country", "o.amount")
)
display(result)Aliases are also required for self-joins, where you join a DataFrame to itself.
When key names differ, for example cust_id on one side and customer on the other, you must use a condition expression, then drop or rename one column.
Nulls never match
In an equality join, a null key does not match anything, including another null. Rows with null keys survive only in outer joins, where they appear unmatched. If you want nulls to match, use the null-safe operator eqNullSafe.
cond = orders["customer"].eqNullSafe(customers["customer"])Check your key columns for nulls before joining. A silent loss of rows in an inner join is often caused by null or differently formatted keys, such as trailing spaces or mixed case.
Row multiplication
If the right side has several rows for one key, each left row is repeated once per match. A join on a non-unique key multiplies rows, and later sums become inflated.
dupes = spark.createDataFrame(
[("alice", "US"), ("alice", "CA"), ("bob", "DE")],
"customer STRING, country STRING",
)
orders.join(dupes, "customer", "left").groupBy().agg(F.count("*")).show()The count is 5, not 4, because alice's two orders each match two rows. Before joining, confirm that the key is unique on the side you expect to be a lookup table.
customers.groupBy("customer").count().filter("count > 1").show()If this returns rows, deduplicate with dropDuplicates(["customer"]) or aggregate first.
How Spark executes a join
Spark chooses a physical strategy. You can see the choice with explain().
- Broadcast hash join: Spark sends the smaller DataFrame to every executor. The large side is not moved across the network. This is the fastest strategy and is chosen automatically when one side is below
spark.sql.autoBroadcastJoinThreshold, which defaults to 10 MB. - Sort-merge join: Both sides are shuffled by the key and sorted. This is the default for two large inputs.
- Cartesian or nested loop joins: Used for cross joins and non-equality conditions. They can be very slow.
joined = orders.join(customers, on="customer", how="left")
joined.explain()Look for BroadcastHashJoin or SortMergeJoin in the plan. Exchange nodes mark shuffles.
You can request a broadcast with a hint when you know a side is small but Spark lacks statistics.
joined = orders.join(F.broadcast(customers), on="customer", how="left")Do not broadcast a large DataFrame. It can exhaust driver or executor memory. On Databricks, adaptive query execution may also convert a sort-merge join to a broadcast join at run time when the real data turns out to be small.
Common errors
- Ambiguous column: both sides have a column with the same name. Join with
on="name", alias the inputs, or drop one column. - Accidental cross join: joining with no condition, or a condition that does not reference both sides. Spark raises an error unless you call
crossJoinor enable it explicitly. Fix the condition rather than disabling the check. - Missing rows after an inner join: check for null, whitespace, case, or type mismatches in the keys. A string key compared with an integer key may be cast implicitly.
- Inflated totals: the right side has duplicate keys. Check uniqueness first.
- Filter on the right side in a left join: a
whereclause such ascountry = 'US'after a left join removes rows with null country, which turns the left join into an inner join. Put right-side conditions in the join condition if you want to keep unmatched rows.
only_us = orders.join(
customers,
(orders["customer"] == customers["customer"]) & (customers["country"] == "US"),
"left",
)Exercise
You run orders.join(customers, "customer", "left") and the result has more rows than orders. What is the most likely cause, and how do you check it?
Show answer
The customers DataFrame has more than one row for at least one customer value, so matching orders are repeated. Check with customers.groupBy("customer").count().filter("count > 1"), then deduplicate or aggregate customers before joining.
Exercise
Which join type returns the orders that have no matching customer, with only the columns of orders?
Show answer
leftanti. For example, orders.join(customers, "customer", "leftanti").