๐ Joins
A join combines rows from two tables by matching values in one or more columns. Joins are how you answer questions like "which floor does each employee sit on?" when that information lives in two different tables.
This tutorial covers every join type in Spark SQL, from INNER JOIN to LEFT ANTI JOIN, plus the traps that produce missing or duplicated rows.
Sample Data
We use the employees view from the introduction and a departments view. Notice two mismatches on purpose: HR has no employees, and Grace has no department.
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
CREATE OR REPLACE TEMP VIEW departments AS
SELECT * FROM VALUES
('Engineering', 3, 500000),
('Sales', 2, 200000),
('Marketing', 2, 150000),
('HR', 1, 80000)
AS departments(dept, floor, budget)
1. How a Join Works
A join looks at every pair of rows, one from each table, and keeps the pairs where the join condition is true:
-- Syntax
SELECT columns
FROM left_table AS l
JOIN right_table AS r
ON l.key = r.key
- The table after
FROMis the left table; the one afterJOINis the right table. ONholds the join condition.- Short aliases such as
eanddkeep queries readable. Use them to say which table each column comes from:e.name,d.floor.
The join type decides what happens to rows that do not find a match. That is the only real difference between the types below.
2. INNER JOIN: Only Matching Rows
INNER JOIN (or just JOIN) keeps only the rows that match on both sides:
SELECT e.name, e.dept, d.floor
FROM employees e
INNER JOIN departments d
ON e.dept = d.dept
ORDER BY e.emp_id
+-----+-----------+-----+
|name |dept |floor|
+-----+-----------+-----+
|Asha |Engineering|3 |
|Ben |Engineering|3 |
|Chen |Sales |2 |
|Divya|Sales |2 |
|Elena|Marketing |2 |
|Farid|Engineering|3 |
+-----+-----------+-----+
Six rows. Grace is missing because her dept is NULL, and HR is missing because nobody works there. An inner join silently drops unmatched rows from both sides.
3. LEFT JOIN: Keep Everything on the Left
LEFT JOIN (also written LEFT OUTER JOIN) keeps every row of the left table. Where there is no match, the right-side columns are NULL:
SELECT e.name, e.dept, d.floor
FROM employees e
LEFT JOIN departments d
ON e.dept = d.dept
ORDER BY e.emp_id
+-----+-----------+-----+
|name |dept |floor|
+-----+-----------+-----+
|Asha |Engineering|3 |
|Ben |Engineering|3 |
|Chen |Sales |2 |
|Divya|Sales |2 |
|Elena|Marketing |2 |
|Farid|Engineering|3 |
|Grace|NULL |NULL |
+-----+-----------+-----+
Grace is back, with floor = NULL. HR is still absent, because it is on the right side.
LEFT JOIN is the most used join in data engineering. A typical pattern is "keep all my facts, and add details from a lookup table where available".
4. RIGHT JOIN: Keep Everything on the Right
RIGHT JOIN is the mirror image: it keeps every row of the right table.
SELECT d.dept, d.floor, e.name
FROM employees e
RIGHT JOIN departments d
ON e.dept = d.dept
ORDER BY d.dept, e.name
+-----------+-----+-----+
|dept |floor|name |
+-----------+-----+-----+
|Engineering|3 |Asha |
|Engineering|3 |Ben |
|Engineering|3 |Farid|
|HR |1 |NULL |
|Marketing |2 |Elena|
|Sales |2 |Chen |
|Sales |2 |Divya|
+-----------+-----+-----+
Now HR appears with no employee name, and Grace is gone. In practice, most people swap the table order and write a LEFT JOIN instead, because it reads more naturally.
5. FULL OUTER JOIN: Keep Everything
FULL OUTER JOIN (or FULL JOIN) keeps all rows from both tables, matched where possible:
SELECT e.name, e.dept AS emp_dept, d.dept AS dept_table, d.floor
FROM employees e
FULL OUTER JOIN departments d
ON e.dept = d.dept
ORDER BY d.dept, e.name
+-----+-----------+-----------+-----+
|name |emp_dept |dept_table |floor|
+-----+-----------+-----------+-----+
|Grace|NULL |NULL |NULL |
|Asha |Engineering|Engineering|3 |
|Ben |Engineering|Engineering|3 |
|Farid|Engineering|Engineering|3 |
|NULL |NULL |HR |1 |
|Elena|Marketing |Marketing |2 |
|Chen |Sales |Sales |2 |
|Divya|Sales |Sales |2 |
+-----+-----------+-----------+-----+
Both Grace (no department) and HR (no employees) appear. Full joins are useful for reconciliation: comparing two sources and finding records that exist in only one of them.
6. LEFT SEMI and LEFT ANTI: "Is There a Match?"
Sometimes you do not want columns from the other table. You only want to know whether a match exists. Spark has two join types for that.
LEFT SEMI JOIN returns left rows that have a match. Which departments have at least one employee?
SELECT d.*
FROM departments d
LEFT SEMI JOIN employees e
ON d.dept = e.dept
ORDER BY d.dept
+-----------+-----+------+
|dept |floor|budget|
+-----------+-----+------+
|Engineering|3 |500000|
|Marketing |2 |150000|
|Sales |2 |200000|
+-----------+-----+------+
Engineering has three employees but appears only once. A semi join never duplicates left rows, and it returns only the left table's columns.
LEFT ANTI JOIN returns left rows that have no match. Which departments have no employees?
SELECT d.*
FROM departments d
LEFT ANTI JOIN employees e
ON d.dept = e.dept
+----+-----+------+
|dept|floor|budget|
+----+-----+------+
|HR |1 |80000 |
+----+-----+------+
And which employees do not belong to a known department?
SELECT e.name, e.dept
FROM employees e
LEFT ANTI JOIN departments d
ON e.dept = d.dept
+-----+----+
|name |dept|
+-----+----+
|Grace|NULL|
+-----+----+
Interview tip: "Find customers with no orders" is an anti join. In other databases you would write
LEFT JOIN ... WHERE right.key IS NULLorNOT EXISTS. In Spark,LEFT ANTI JOINsays it directly, and theNOT EXISTSform is turned into the same anti join behind the scenes.
7. CROSS JOIN: Every Combination
CROSS JOIN has no condition. It pairs every row on the left with every row on the right, so the result has left rows x right rows rows:
SELECT d.dept, s.shift
FROM departments d
CROSS JOIN VALUES ('Day'), ('Night') AS s(shift)
ORDER BY d.dept, s.shift
+-----------+-----+
|dept |shift|
+-----------+-----+
|Engineering|Day |
|Engineering|Night|
|HR |Day |
|HR |Night|
|Marketing |Day |
|Marketing |Night|
|Sales |Day |
|Sales |Night|
+-----------+-----+
Four departments times two shifts gives eight rows. Cross joins are handy for building every combination (for example, every store for every date), but they grow fast: two tables of 100,000 rows give 10 billion rows. Use them on purpose and only with small tables.
8. Self Join: A Table Joined to Itself
A table can be joined to itself, using two different aliases. Our manager_id column points to another row in employees, so a self join finds each employee's manager:
SELECT e.name AS employee,
m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.emp_id
ORDER BY e.emp_id
+--------+-------+
|employee|manager|
+--------+-------+
|Asha |NULL |
|Ben |Asha |
|Chen |Asha |
|Divya |Chen |
|Elena |Asha |
|Farid |Ben |
|Grace |NULL |
+--------+-------+
Think of e and m as two copies of the same table, one playing "employee" and one playing "manager". We used LEFT JOIN so that Asha and Grace, who have no manager, are not dropped.
9. ON vs USING
When the key column has the same name in both tables, USING (column) is a shorter alternative to ON. It also merges the key into one output column.
With ON and SELECT *, you get dept twice:
SELECT *
FROM employees e
JOIN departments d
ON e.dept = d.dept
WHERE e.emp_id IN (1, 3)
ORDER BY e.emp_id
+------+----+-----------+------+----------+----------+---------+-----------+-----+------+
|emp_id|name|dept |salary|hire_date |manager_id|city |dept |floor|budget|
+------+----+-----------+------+----------+----------+---------+-----------+-----+------+
|1 |Asha|Engineering|95000 |2019-03-15|NULL |Bengaluru|Engineering|3 |500000|
|3 |Chen|Sales |60000 |2021-01-10|1 |Mumbai |Sales |2 |200000|
+------+----+-----------+------+----------+----------+---------+-----------+-----+------+
With USING, dept appears once, as the first column:
SELECT *
FROM employees
JOIN departments USING (dept)
WHERE emp_id IN (1, 3)
ORDER BY emp_id
+-----------+------+----+------+----------+----------+---------+-----+------+
|dept |emp_id|name|salary|hire_date |manager_id|city |floor|budget|
+-----------+------+----+------+----------+----------+---------+-----+------+
|Engineering|1 |Asha|95000 |2019-03-15|NULL |Bengaluru|3 |500000|
|Sales |3 |Chen|60000 |2021-01-10|1 |Mumbai |2 |200000|
+-----------+------+----+------+----------+----------+---------+-----+------+
Use ON when the column names differ (such as e.manager_id = m.emp_id) or when the condition is more than a simple equality.
10. Joining on Multiple Columns
Some keys need more than one column. Here, a travel allowance depends on both the department and the city:
CREATE OR REPLACE TEMP VIEW allowances AS
SELECT * FROM VALUES
('Engineering', 'Bengaluru', 5000),
('Engineering', 'Pune', 3000),
('Sales', 'Mumbai', 4000),
('Sales', 'Delhi', 2500)
AS allowances(dept, city, allowance)
Combine the conditions with AND:
SELECT e.name, e.dept, e.city, a.allowance
FROM employees e
JOIN allowances a
ON e.dept = a.dept
AND e.city = a.city
ORDER BY e.emp_id
+-----+-----------+---------+---------+
|name |dept |city |allowance|
+-----+-----------+---------+---------+
|Asha |Engineering|Bengaluru|5000 |
|Ben |Engineering|Pune |3000 |
|Chen |Sales |Mumbai |4000 |
|Divya|Sales |Mumbai |4000 |
|Farid|Engineering|Bengaluru|5000 |
+-----+-----------+---------+---------+
Asha and Farid share the same (Engineering, Bengaluru) key, so both get 5,000. Joining on dept alone would have matched each engineer with two allowance rows, which leads to the next trap.
11. Duplicate Matches Multiply Rows
If a key appears more than once on both sides, every pair matches. This is called a many-to-many join, and it is the most common reason for numbers that are "too big" after a join.
CREATE OR REPLACE TEMP VIEW projects AS
SELECT * FROM VALUES
('Apollo', 'Engineering'),
('Hermes', 'Engineering'),
('Zeus', 'Sales')
AS projects(project, dept)
Engineering has 3 employees and 2 projects, so the join produces 3 x 2 = 6 Engineering rows. Watch what that does to a salary total:
SELECT e.dept,
COUNT(*) AS joined_rows,
SUM(e.salary) AS payroll_after_join
FROM employees e
JOIN projects p
ON e.dept = p.dept
GROUP BY e.dept
ORDER BY e.dept
+-----------+-----------+------------------+
|dept |joined_rows|payroll_after_join|
+-----------+-----------+------------------+
|Engineering|6 |518000 |
|Sales |2 |125000 |
+-----------+-----------+------------------+
Engineering's real payroll is 259,000 (95,000 + 82,000 + 82,000), but the join counts each salary twice, giving 518,000.
Common mistake: Aggregating after a join without checking that the key is unique on one side. Before joining, ask: "Can this key appear more than once in each table?" If yes, aggregate one side first, or use a semi join if you only need to know that a match exists.
A quick check is to compare row counts: SELECT COUNT(*) before and after the join. If a LEFT JOIN returns more rows than its left table, some keys matched more than once.
12. NULL Keys Never Match
A join condition a.key = b.key uses normal equality, and NULL = NULL is not true (see Handling NULLs). So rows with a NULL key never match, not even with another NULL:
SELECT l.k, r.v
FROM VALUES ('a'), (NULL) AS l(k)
JOIN VALUES ('a', 1), (NULL, 2) AS r(k, v)
ON l.k = r.k
+---+---+
|k |v |
+---+---+
|a |1 |
+---+---+
If NULL should match NULL (for example, when comparing two snapshots of the same data), use the null-safe operator <=>:
SELECT l.k, r.v
FROM VALUES ('a'), (NULL) AS l(k)
JOIN VALUES ('a', 1), (NULL, 2) AS r(k, v)
ON l.k <=> r.k
ORDER BY r.v
+----+---+
|k |v |
+----+---+
|a |1 |
|NULL|2 |
+----+---+
This is also why Grace was dropped by the inner join in section 2: her dept is NULL, so it cannot equal anything.
13. Filtering a LEFT JOIN: ON vs WHERE
This trap catches experienced engineers. Suppose you want every department, with its employees who earn more than 80,000 listed next to it.
Putting the salary filter in WHERE looks natural:
SELECT d.dept, e.name, e.salary
FROM departments d
LEFT JOIN employees e
ON d.dept = e.dept
WHERE e.salary > 80000
ORDER BY d.dept, e.name
+-----------+-----+------+
|dept |name |salary|
+-----------+-----+------+
|Engineering|Asha |95000 |
|Engineering|Ben |82000 |
|Engineering|Farid|82000 |
+-----------+-----+------+
Sales, Marketing and HR have disappeared. WHERE runs after the join. For departments without a high earner, e.salary is NULL, NULL > 80000 is not true, and WHERE drops the row. The LEFT JOIN has quietly become an INNER JOIN.
Move the filter into ON, and it only decides which employees match. Every department survives:
SELECT d.dept, e.name, e.salary
FROM departments d
LEFT JOIN employees e
ON d.dept = e.dept
AND e.salary > 80000
ORDER BY d.dept, e.name
+-----------+-----+------+
|dept |name |salary|
+-----------+-----+------+
|Engineering|Asha |95000 |
|Engineering|Ben |82000 |
|Engineering|Farid|82000 |
|HR |NULL |NULL |
|Marketing |NULL |NULL |
|Sales |NULL |NULL |
+-----------+-----+------+
Rule of thumb for outer joins:
| Filter on... | Put it in | Why |
|---|---|---|
The table whose rows you keep (left side of LEFT JOIN) | WHERE | It filters the final rows as expected |
The other table (right side of LEFT JOIN) | ON | In WHERE it would remove unmatched rows |
For an INNER JOIN, ON and WHERE give the same result, so choose whichever reads better.
14. Ambiguous Column Names
When both tables have a column with the same name, Spark cannot guess which one you mean:
SELECT name, dept, floor
FROM employees e
JOIN departments d
ON e.dept = d.dept
[AMBIGUOUS_REFERENCE] Reference `dept` is ambiguous, could be: [`d`.`dept`, `e`.`dept`].; line 1 pos 13
The fix is to prefix the column with its table alias, for example e.dept. A good habit is to prefix every column in a join query, even when it is not ambiguous. It makes the query easier to read and protects it if a column with the same name is added to the other table later.
15. Join Types at a Glance
| Join | Matched rows | Unmatched left rows | Unmatched right rows | Columns returned |
|---|---|---|---|---|
INNER JOIN | Yes | Dropped | Dropped | Both tables |
LEFT JOIN | Yes | Kept, right side NULL | Dropped | Both tables |
RIGHT JOIN | Yes | Dropped | Kept, left side NULL | Both tables |
FULL OUTER JOIN | Yes | Kept | Kept | Both tables |
LEFT SEMI JOIN | Yes, once per left row | Dropped | Dropped | Left table only |
LEFT ANTI JOIN | Dropped | Kept | Dropped | Left table only |
CROSS JOIN | Every pair | n/a | n/a | Both tables |
This tutorial is about what joins return. How Spark executes them (broadcast joins, sort-merge joins and shuffles) is covered in the theory article on Spark join strategies.
Try It in the Online Compiler
Copy this into the PySpark Online Compiler to try outer and anti joins:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Joins").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")
spark.sql("""
CREATE OR REPLACE TEMP VIEW departments AS
SELECT * FROM VALUES
('Engineering', 3, 500000),
('Sales', 2, 200000),
('Marketing', 2, 150000),
('HR', 1, 80000)
AS departments(dept, floor, budget)
""")
spark.sql("""
SELECT e.name, e.dept AS emp_dept, d.dept AS dept_table, d.floor
FROM employees e
FULL OUTER JOIN departments d ON e.dept = d.dept
ORDER BY d.dept, e.name
""").show(truncate=False)
spark.sql("""
SELECT d.*
FROM departments d
LEFT ANTI JOIN employees e ON d.dept = e.dept
""").show(truncate=False)
spark.sql("""
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.emp_id
ORDER BY e.emp_id
""").show(truncate=False)
Summary
- The join type only decides what happens to unmatched rows:
INNERdrops them,LEFT/RIGHT/FULLkeep them with NULLs. LEFT SEMI JOINkeeps left rows that have a match (no duplicates);LEFT ANTI JOINkeeps left rows that have none.CROSS JOINreturns every combination, so its size is the product of both tables.- A self join uses two aliases of the same table, for example to look up managers.
USING (col)merges the key into one column;ONkeeps both and allows any condition.- Duplicate keys on both sides multiply rows and inflate totals. Check row counts before and after a join.
- NULL keys never match with
=; use<=>if they should. - In a
LEFT JOIN, filters on the right table belong inON, notWHERE. - Prefix columns with table aliases to avoid ambiguous-reference errors.
Next, you will learn how to stack results on top of each other with UNION, INTERSECT and EXCEPT.