Skip to content
Bronze 5 min read · Joins 3 practice problems ↓

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

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

howKeepsUnmatched rows
inner (default)Only rows with a match on both sidesDropped from both sides
leftEvery left rowRight columns are null
rightEvery right rowLeft columns are null
full (outer)Every row from both sidesThe 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

namedept
AshaEngineering
BenSales
DevHR
Faridnull

Output

namedeptfloor
AshaEngineering3
BenSales1
DevHRnull
Faridnullnull

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

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000null
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002

Input: departments

deptfloor
Engineering3
Sales1
Finance2
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".

PySparkSpark SQL · Check key uniqueness before joining
departments.groupBy("dept").count().filter("count > 1").show()
SELECT dept, COUNT(*) FROM departments
GROUP BY dept HAVING COUNT(*) > 1

Ambiguous column names

  • on="dept" or on=["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, and select("dept") fails as ambiguous. Refer to a["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") then F.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

The small side is sent to every executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → and built into a hash table. The large side is not shuffledshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → at all. Used automatically when one side is under 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 →

Both sides are shuffled by key and sorted, then merged. The default for two large tables. Two shuffles and two sorts: the expensive case.

Shuffle hash join

Both sides shuffled, the smaller partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → side hashed instead of sorted. Chosen in some cases, for example by AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → when partitions are small enough.

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 eqNullSafe if nulls should match.
  • Filtering the right table in WHERE after a left join — WHERE d.floor > 1 removes 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?"

Yes. A left join guarantees every left row appears at least once, not exactly once. If the right side has duplicate keys, each left row is repeated once per match. Fix it by deduplicating the right side, or aggregating it to one row per key, before joining.

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'?"
Join on a list of column names (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?"
An inner join drops orders with no matching customer. Run a left_anti join of orders against customers to get the missing ones, then look at the keys: nulls, type mismatches (string vs int), leading zeros, whitespace or case. Decide whether to fix the data or use a left join and flag unmatched rows.
Trap"Joining on a key that is null on both sides matches those rows."
No. null = null is unknown, so equi-joins never match null keys. Use eqNullSafe (<=>) if nulls should match, knowing that all null keys then land in one task.

Check yourself

3 questions

Key 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

See all 19 problems →

Keep going

Up next · Combine and summarise · lesson 4 of 4 · 6 min read
spark.sql and temp views
Mix SQL and DataFrames: register views, run spark.sql, and pass parameters safely.

Related lessons

Previous: dropDuplicates

Primary sources: DataFrame.join · JOIN (Spark SQL)