join
Orders are in one table and customers in another; to see each order with its customer's city you join them. This lesson shows what each join type keeps, how repeated keys multiply rows, how to avoid confusing column names, and the two ways Spark actually carries out a join.
Step 1 · PySpark functions · Bronze · Combine and summarise, lesson 3 of 4
On this page
Show code in
Every code block on the page follows this.
Read first: select · filter / where (skip if you know them)
In plain words first
Imagine two stacks of cards: orders, each with a customer id, and customers, each with an id and a city. You take each order card and clip to it the customer card with the same id. Orders with no matching customer, and customers with no orders, are the interesting cases: do you keep them or throw them away?
The join type is that decision. An inner join keeps only clipped pairs; a left join keeps every order, with an empty space where no customer was found.
What it does
For each row on the left, Spark finds the rows on the right whose keys match, and outputs one combined row per match. Rows that match nothing are dropped or kept with nullsnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →, depending on how.
The four everyday join types
| how | Keeps | Unmatched rows |
|---|---|---|
| inner (default) | Only rows with a match on both sides | Dropped from both sides |
| left | Every left row | Right columns are null |
| right | Every right row | Left columns are null |
| full (outer) | Every row from both sides | The missing side is null |
Spark also has left_semi and left_anti (filter by existence) and cross. They get their own lesson.
Step by step
A left join of employees to departments on dept:
employees (left) + departments
| name | dept |
|---|---|
| Asha | Engineering |
| Ben | Sales |
| Dev | HR |
| Farid | null |
Output
| name | dept | floor |
|---|---|---|
| Asha | Engineering | 3 |
| Ben | Sales | 1 |
| Dev | HR | null |
| Farid | null | null |
HR has no row in departments, so Dev gets a null floor. Farid's null key matches nothing, because null never equals null. Finance has no employee and disappears: it is on the right.
Run the example
Input: employees
| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Asha | Engineering | 72000 | null |
| 2 | Ben | Sales | 48000 | 1 |
| 3 | Chitra | Engineering | 95000 | 1 |
| 4 | Dev | HR | 51000 | 1 |
| 5 | Esha | Sales | 50000 | 2 |
| 6 | Farid | null | 39000 | 2 |
Input: departments
| dept | floor |
|---|---|
| Engineering | 3 |
| Sales | 1 |
| Finance | 2 |
result = (employees .join(departments, on="dept", how="left") .select("name", "dept", "floor") .orderBy("name"))
SELECT e.name, e.dept, d.floor FROM employees e LEFT JOIN departments d ON e.dept = d.dept ORDER BY e.name
Try how="inner", "right" and "full" and watch which rows appear.
The fan-out trap
A join outputs one row per matching pair. If a key appears 3 times on the left and 4 times on the right, that key produces 12 rows. This is the most common source of "my totals doubled after a join".
departments.groupBy("dept").count().filter("count > 1").show()
SELECT dept, COUNT(*) FROM departments GROUP BY dept HAVING COUNT(*) > 1
Ambiguous column names
on="dept"oron=["dept", "year"]: Spark joins on equality and keeps one copy of each key column. Use this whenever the names match.on=a.dept == b.dept: both copies are kept, andselect("dept")fails as ambiguous. Refer toa["dept"], or alias the DataFramesDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more →:a.alias("e")thenF.col("e.dept").
Under the hood: how Spark joins Optional deep dive
Broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more → hash join
spark.sql.autoBroadcastJoinThreshold (10 MB by default).Sort-merge joinsort-merge join: Spark's default join for two large tables: both sides are shuffled and sorted by the key, then matched in one pass. Learn more →
Shuffle hash join
You can force a broadcast with F.broadcast(small_df) or the SQL hint /*+ BROADCAST(d) */. The Broadcast joins lesson covers when that backfires.
Common mistakes
- Joining on keys with duplicates you did not expect — Row counts explodeexplode: Turn each element of an array into a row of its own, copying the other columns. Learn more → and sums double. Check uniqueness of the key on at least one side.
- Expecting null keys to match — In an equality join, null never equals null. Use
eqNullSafeif nulls should match. - Filtering the right table in WHERE after a left join —
WHERE d.floor > 1removes the null rows the left join just kept, turning it into an inner join. Put the condition in the ON clause or filter the right side before joining.
Key takeaways
- The join type only decides what happens to unmatched rows.
- Each matching pair is a row, so duplicate keys multiply rows.
- Join with
on="col"to keep a single key column. - Small tables are broadcast; two large ones use a sort-merge join with two shuffles.
Interview prep
THE QUESTION
"After a left join, the row count went up. Is that possible?"
Avoid: "no, a left join keeps the left row count". It keeps every left row at least once; duplicate keys on the right multiply rows.
Follow-ups · answer out loud, then open
Follow-up"How do you avoid ambiguous column errors after joining two DataFrames that both have 'id' and 'updated_at'?"
on=["id"]) so the key appears once, alias the DataFrames (a = df1.alias("a")) and select F.col("a.updated_at"), or rename conflicting columns before the join.Scenario"A join of orders to customers drops 2% of orders. How do you investigate?"
Trap"Joining on a key that is null on both sides matches those rows."
eqNullSafe (<=>) if nulls should match, knowing that all null keys then land in one task.Check yourself
3 questionsKey K appears 2 times on the left and 3 times on the right. How many rows does an inner join output for K?
Show the answer
6. Every left row pairs with every matching right row: 2 × 3 = 6.
A left join keeps a left row whose key is null. What are its right-side columns?
Show the answer
null. Null never equals anything in an equality join, so the row has no match and the right columns are null.
Why does a.join(b, a.id == b.id).select("id") fail?
Show the answer
Both id columns are kept, so the reference is ambiguous. An expression join keeps both columns. Join with on="id" to keep one, or select a["id"].
Practise this
Problems that use join, graded on hidden tests
- Order Lines with Product DetailsJoins Easy
- Employees and Their DepartmentsJoins Medium
- Year-over-Year GrowthJoins Medium
Keep going
Up next · Combine and summarise · lesson 4 of 4 · 6 min readspark.sql and temp views
Mix SQL and DataFrames: register views, run spark.sql, and pass parameters safely.
Related lessons
left_semi / left_antiSpark internals · 8 min read
Join strategiesPySpark functions · 4 min read
eqNullSafe (<=>)
Previous: dropDuplicates
Primary sources: DataFrame.join · JOIN (Spark SQL)