Database JOIN
What you will learn
- Why data split across tables must be joined back together
- How JOIN ... ON matches a foreign key to a primary key
- How to join three tables and use table aliases
- What LEFT JOIN adds
- Why a join without a condition is dangerous
This lesson runs on the sample database you chose in lesson 4.1. Use the Example data picker at the top to change it, and press Tables to see how the tables are linked (the FK -> marks).
1. Why join?
The orders table stores customer_id = 17, not a name. A customer's name is stored once, in customers, and orders points to it with a foreign key (chapter 3).
The accounts table stores customer_id = 17, not a name. A customer's name is stored once, in customers, and accounts points to it with a foreign key (chapter 3).
The sections table stores course_id = 7, not a title. A course's title is stored once, in courses, and sections points to it with a foreign key (chapter 3).
That avoids repeating the name in every row, but to read a friendly report we must put the tables back together. That is what JOIN does.
2. INNER JOIN
Join two tables where the foreign key equals the primary key it points to:
SELECT o.order_id, c.first_name, c.last_name, o.order_date
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
ORDER BY o.order_id
LIMIT 5;
order_id first_name last_name order_date
-------- ---------- --------- ----------
1 Dana Wang 2025-04-23
2 Ugo Das 2024-01-21
3 Jin Bianchi 2025-05-03
4 Sara Nair 2026-08-18
5 Bruno Zhang 2024-05-26
(5 rows)
SELECT a.account_id, c.full_name, a.account_type
FROM accounts a
JOIN customers c ON a.customer_id = c.customer_id
ORDER BY a.account_id
LIMIT 5;
account_id full_name account_type
---------- ------------- ------------
1 Leo Kumar checking
2 Hana Kim savings
3 Vera Banerjee savings
4 Olga Garcia checking
5 Amir Singh checking
(5 rows)
SELECT s.section_id, c.code, c.title, s.term
FROM sections s
JOIN courses c ON s.course_id = c.course_id
ORDER BY s.section_id
LIMIT 5;
section_id code title term
---------- ------- ---------------------- -----------
1 MATH101 Foundations of Algebra 2025-Autumn
2 MATH201 Geometry 2025-Spring
3 MATH201 Geometry 2025-Autumn
4 MATH201 Geometry 2026-Spring
5 MATH301 Statistics 2025-Spring
(5 rows)
JOIN (short for INNER JOIN) keeps only pairs of rows where the ON condition is true. Each row of the first table found its partner row. When two tables share a column name, write the table name (or its alias) first, as in o.order_id.
3. Aliases and three tables
Long table names get tiring, so give each table a short alias. Chain more JOINs to bring in more tables:
SELECT o.order_id, c.last_name AS customer, p.name AS product, oi.quantity, ROUND(oi.quantity * oi.unit_price, 2) AS total
FROM order_items AS oi
JOIN orders AS o ON oi.order_id = o.order_id
JOIN customers AS c ON o.customer_id = c.customer_id
JOIN products AS p ON oi.product_id = p.product_id
ORDER BY o.order_id, oi.line_no
LIMIT 6;
order_id customer product quantity total
-------- -------- -------------- -------- -----
1 Wang Pruning shears 1 29.5
1 Wang Camping mug 1 21.6
1 Wang Storage box 1 24.0
1 Wang Rain poncho 1 32.45
2 Das Board game 4 48.0
3 Bianchi Day backpack 2 9.0
(6 rows)
SELECT t.txn_id, c.full_name AS customer, t.kind, t.amount_cents / 100.0 AS amount
FROM transactions AS t
JOIN accounts AS a ON t.account_id = a.account_id
JOIN customers AS c ON a.customer_id = c.customer_id
ORDER BY t.txn_id
LIMIT 6;
txn_id customer kind amount
------ ------------ ---------- ------
1 Diego Zhang deposit 548.0
2 Ibrahim Abdi deposit 532.0
3 Paulo Meyer deposit 760.0
4 Diego Zhang withdrawal 239.0
5 Paulo Meyer fee 10.0
6 Diego Zhang withdrawal 70.0
(6 rows)
SELECT st.first_name, st.last_name, sec.term, e.grade
FROM enrollments AS e
JOIN students AS st ON e.student_id = st.student_id
JOIN sections AS sec ON e.section_id = sec.section_id
ORDER BY e.student_id, e.section_id
LIMIT 6;
first_name last_name term grade
---------- --------- ----------- -----
Vera Khan 2026-Spring NULL
Vera Khan 2025-Spring 49.2
Vera Khan 2025-Spring 60.8
Elena Haque 2026-Spring NULL
Elena Haque 2025-Autumn 55.3
Elena Haque 2025-Autumn 80.4
(6 rows)
Now the report reads like a real list. Each ON links one foreign key to the primary key it points to.
4. LEFT JOIN: keep the unmatched
Some rows have no partner, so they vanish from an inner join. LEFT JOIN keeps every row of the left table (the one before the word JOIN) and fills the right side with NULL when nothing matches. In SQLite NULL sorts first, so ordering by the right-hand column puts the unmatched rows on top:
SELECT c.customer_id, c.last_name, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
ORDER BY o.order_id, c.customer_id
LIMIT 5;
customer_id last_name order_id
----------- --------- --------
14 Khan NULL
19 Sato NULL
22 Lopez NULL
23 Wang NULL
25 Uddin NULL
(5 rows)
SELECT a.account_id, a.account_type, k.card_id
FROM accounts a
LEFT JOIN cards k ON k.account_id = a.account_id
ORDER BY k.card_id, a.account_id
LIMIT 5;
account_id account_type card_id
---------- ------------ -------
2 savings NULL
3 savings NULL
7 savings NULL
8 savings NULL
9 savings NULL
(5 rows)
SELECT s.student_id, s.last_name, e.section_id
FROM students s
LEFT JOIN enrollments e ON e.student_id = s.student_id
ORDER BY e.section_id, s.student_id
LIMIT 5;
student_id last_name section_id
---------- --------- ----------
15 Tanaka NULL
76 Jensen NULL
135 Lee NULL
137 Park NULL
152 Lee NULL
(5 rows)
A handy trick: filter on IS NULL to find rows with no match:
Customers who never ordered:
SELECT c.customer_id, c.first_name, c.last_name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
ORDER BY c.customer_id
LIMIT 5;
customer_id first_name last_name
----------- ---------- ---------
14 Leo Khan
19 Dana Sato
22 Jin Lopez
23 Bruno Wang
25 Tariq Uddin
(5 rows)
Accounts with no card:
SELECT a.account_id, a.account_type
FROM accounts a
LEFT JOIN cards k ON k.account_id = a.account_id
WHERE k.card_id IS NULL
ORDER BY a.account_id
LIMIT 5;
account_id account_type
---------- ------------
2 savings
3 savings
7 savings
8 savings
9 savings
(5 rows)
Students who are not enrolled in any section:
SELECT s.student_id, s.first_name, s.last_name
FROM students s
LEFT JOIN enrollments e ON e.student_id = s.student_id
WHERE e.student_id IS NULL
ORDER BY s.student_id
LIMIT 5;
student_id first_name last_name
---------- ---------- ---------
15 Tariq Tanaka
76 Vik Jensen
135 Rafi Lee
137 Gita Park
152 Uma Lee
(5 rows)
5. Join, then summarise
Joins combine with GROUP BY (lesson 4.4):
Total spent per customer (cancelled orders left out):
SELECT c.customer_id, c.last_name, ROUND(SUM(oi.quantity * oi.unit_price), 2) AS spent
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY c.customer_id
ORDER BY spent DESC, c.customer_id
LIMIT 5;
customer_id last_name spent
----------- --------- -------
72 Silva 1776.7
395 Lee 1604.92
404 Meyer 1600.02
59 Ito 1587.68
134 Kamau 1571.75
(5 rows)
The name columns are not in GROUP BY, but they are the same for every row of one customer, so the result is meaningful (the rule of thumb in lesson 4.4 is about columns that differ inside a group).
Total deposited per customer:
SELECT c.customer_id, c.full_name, SUM(t.amount_cents) / 100.0 AS deposited
FROM customers c
JOIN accounts a ON a.customer_id = c.customer_id
JOIN transactions t ON t.account_id = a.account_id
WHERE t.kind = 'deposit'
GROUP BY c.customer_id
ORDER BY deposited DESC, c.customer_id
LIMIT 5;
customer_id full_name deposited
----------- ----------- ---------
96 Rosa Kumar 19222.0
260 Arjun Sato 16021.0
133 Leo Alvarez 14797.0
284 Leo Nair 13695.0
234 Uma Reyes 13647.0
(5 rows)
The name is the same for every row of one customer, so the result is meaningful (the rule of thumb in lesson 4.4 is about columns that differ inside a group).
Average grade per course (grades not given yet are ignored):
SELECT c.code, c.title, ROUND(AVG(e.grade), 1) AS avg_grade
FROM courses c
JOIN sections s ON s.course_id = c.course_id
JOIN enrollments e ON e.section_id = s.section_id
GROUP BY c.course_id
ORDER BY avg_grade DESC, c.code
LIMIT 5;
code title avg_grade
------ --------- ---------
ART101 Drawing 76.3
HUM201 Geography 73.2
HUM301 Civics 73.1
ART202 Drama 72.8
SCI201 Chemistry 72.0
(5 rows)
The code and title are the same for every row of one course, so the result is meaningful (the rule of thumb in lesson 4.4 is about columns that differ inside a group).
6. The forgotten ON
A join without a condition pairs every row with every row (a "cross join"):
SELECT COUNT(*) AS customers FROM customers;
SELECT COUNT(*) AS products FROM products;
SELECT COUNT(*) AS rows_without_on FROM customers, products;
customers
---------
420
(1 row)
products
--------
45
(1 row)
rows_without_on
---------------
18900
(1 row)
SELECT COUNT(*) AS customers FROM customers;
SELECT COUNT(*) AS branches FROM branches;
SELECT COUNT(*) AS rows_without_on FROM customers, branches;
customers
---------
300
(1 row)
branches
--------
6
(1 row)
rows_without_on
---------------
1800
(1 row)
SELECT COUNT(*) AS students FROM students;
SELECT COUNT(*) AS courses FROM courses;
SELECT COUNT(*) AS rows_without_on FROM students, courses;
students
--------
360
(1 row)
courses
-------
19
(1 row)
rows_without_on
---------------
6840
(1 row)
The third number is the first times the second: meaningless pairs. With big tables this explodes (a million rows times a million rows). Always write the ON condition.
7. A table joined to itself, and other join types
A table can be joined to itself (a self join) by giving it two aliases. Compare each pair, and write a.id < b.id so each pair appears once and nobody is paired with themselves:
Which customers live in the same city?
SELECT a.last_name AS customer, b.last_name AS same_city_as, a.city
FROM customers a
JOIN customers b ON a.city = b.city AND a.customer_id < b.customer_id
ORDER BY a.customer_id, b.customer_id
LIMIT 5;
customer same_city_as city
-------- ------------ -----
Ahmed Ahmed Leeds
Ahmed Nair Leeds
Ahmed Rahman Leeds
Ahmed Hassan Leeds
Ahmed Ito Leeds
(5 rows)
Self joins also read hierarchies stored in one table, such as employees and their managers (lesson 3.9):
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.employee_id
ORDER BY e.employee_id
LIMIT 5;
employee manager
------------- -------------
Isla Banerjee Chen Nguyen
Gita Uddin Chen Nguyen
Mina Kamau Isla Banerjee
Yusuf Kumar Isla Banerjee
Kofi Bianchi Isla Banerjee
(5 rows)
Which customers live in the same city?
SELECT a.full_name AS customer, b.full_name AS same_city_as, a.city
FROM customers a
JOIN customers b ON a.city = b.city AND a.customer_id < b.customer_id
ORDER BY a.customer_id, b.customer_id
LIMIT 5;
customer same_city_as city
--------- ------------ ----
Chen Park Grace Kamau Lima
Chen Park Ines Cohen Lima
Chen Park Kofi Nair Lima
Chen Park Uma Garcia Lima
Chen Park Gita Khan Lima
(5 rows)
Self joins also read hierarchies stored in one table, such as employees and their managers (lesson 3.9).
Which teachers work in the same department?
SELECT a.name AS teacher, b.name AS same_department_as, a.department_id
FROM teachers a
JOIN teachers b ON a.department_id = b.department_id AND a.teacher_id < b.teacher_id
ORDER BY a.teacher_id, b.teacher_id
LIMIT 5;
teacher same_department_as department_id
------------ ------------------ -------------
Noah Fischer Liam Patel 6
Noah Fischer Hugo Hassan 6
Noah Fischer Arjun Perez 6
Noah Fischer Ibrahim Jensen 6
Noah Fischer Sven Okafor 6
(5 rows)
Self joins also read hierarchies stored in one table, such as employees and their managers (lesson 3.9).
Besides inner and left joins there are a few more kinds. This is the full family:
| Join | Keeps |
|---|---|
INNER JOIN (or just JOIN) |
only rows that match on both sides |
LEFT JOIN |
all left rows, matched right rows or NULL |
RIGHT JOIN |
all right rows, matched left rows or NULL (the same as a left join with the tables swapped) |
FULL JOIN |
all rows from both sides, with NULL where there is no match |
CROSS JOIN |
every left row paired with every right row (no ON) |
SQLite supports RIGHT and FULL joins from version 3.39 (the browser's SQLite is exactly 3.39.0); not every system or older version does, so many people write everything as a left join. Two of them:
SELECT c.customer_id, c.last_name, o.order_id
FROM customers c
FULL JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_id IS NULL OR o.order_id IS NULL
ORDER BY c.customer_id
LIMIT 5;
SELECT c.last_name, cat.name AS category
FROM customers c
CROSS JOIN categories cat
WHERE c.customer_id = 1;
customer_id last_name order_id
----------- --------- --------
14 Khan NULL
19 Sato NULL
22 Lopez NULL
23 Wang NULL
25 Uddin NULL
(5 rows)
last_name category
--------- ----------
Ahmed Fitness
Ahmed Furniture
Ahmed Garden
Ahmed Home
Ahmed Kitchen
Ahmed Office
Ahmed Outdoor
Ahmed Sport
Ahmed Stationery
Ahmed Toys
(10 rows)
SELECT a.account_id, a.account_type, k.card_id
FROM accounts a
FULL JOIN cards k ON k.account_id = a.account_id
WHERE a.account_id IS NULL OR k.card_id IS NULL
ORDER BY a.account_id
LIMIT 5;
SELECT c.full_name, b.name AS branch
FROM customers c
CROSS JOIN branches b
WHERE c.customer_id = 1;
account_id account_type card_id
---------- ------------ -------
2 savings NULL
3 savings NULL
7 savings NULL
8 savings NULL
9 savings NULL
(5 rows)
full_name branch
--------- ----------
Chen Park Airport
Chen Park Central
Chen Park Harbour
Chen Park Old Town
Chen Park Riverside
Chen Park University
(6 rows)
SELECT s.student_id, s.last_name, e.section_id
FROM students s
FULL JOIN enrollments e ON e.student_id = s.student_id
WHERE s.student_id IS NULL OR e.student_id IS NULL
ORDER BY s.student_id
LIMIT 5;
SELECT t.name AS teacher, d.name AS department
FROM teachers t
CROSS JOIN departments d
WHERE t.teacher_id = 1;
student_id last_name section_id
---------- --------- ----------
15 Tanaka NULL
76 Jensen NULL
135 Lee NULL
137 Park NULL
152 Lee NULL
(5 rows)
teacher department
------------ -----------
Noah Fischer Arts
Noah Fischer Computing
Noah Fischer Humanities
Noah Fischer Languages
Noah Fischer Mathematics
Noah Fischer Science
(6 rows)
The first query lists rows that have no partner on either side. Foreign keys make sure there are no rows on the right without a partner on the left, so only left rows show up. The second pairs one row with every row of another table, which is useful on purpose, for example to build a list of every combination. The complete SQL language, with more joins and exercises, is the subject of the next course.
Worked example: the biggest of one kind
Who bought a mug, and when? (Ceramic mug is one of the products.)
SELECT c.last_name, o.order_date, oi.quantity
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p ON p.product_id = oi.product_id
WHERE p.name = 'Ceramic mug'
ORDER BY o.order_date, o.order_id
LIMIT 5;
last_name order_date quantity
--------- ---------- --------
Perez 2024-01-24 1
Nair 2024-01-30 3
Nair 2024-03-04 2
Eze 2024-03-09 1
Abdi 2024-03-09 1
(5 rows)
Which customers made the biggest withdrawals?
SELECT c.full_name, t.txn_date, t.amount_cents / 100.0 AS amount
FROM transactions t
JOIN accounts a ON a.account_id = t.account_id
JOIN customers c ON c.customer_id = a.customer_id
WHERE t.kind = 'withdrawal'
ORDER BY t.amount_cents DESC, t.txn_id
LIMIT 5;
full_name txn_date amount
----------- ---------- ------
Jin Fischer 2021-07-29 300.0
Chen Lee 2022-04-12 300.0
Leo Alvarez 2022-08-01 300.0
Leo Nair 2023-09-21 300.0
Kofi Nair 2023-12-01 300.0
(5 rows)
Who is enrolled in Programming, and in which term?
SELECT st.first_name, st.last_name, sec.term
FROM enrollments e
JOIN students st ON st.student_id = e.student_id
JOIN sections sec ON sec.section_id = e.section_id
JOIN courses c ON c.course_id = sec.course_id
WHERE c.title = 'Programming'
ORDER BY sec.term, st.student_id
LIMIT 5;
first_name last_name term
---------- --------- -----------
Sven Tanaka 2025-Autumn
Leo Zhang 2025-Autumn
Bruno Torres 2025-Autumn
Sven Park 2025-Autumn
Ibrahim Nair 2025-Autumn
(5 rows)
The joins attach names to the rows, WHERE keeps only the rows you ask about, and ORDER BY with LIMIT shows the first few. (All data is made up.)
Common mistakes
- Forgetting
ON, which gives every combination of rows. - Self joining without
a.id < b.id, which pairs every row with itself and lists each pair twice. - Joining on the wrong columns. Join a foreign key to the key it references.
- Expecting inner joins to keep unmatched rows. Use
LEFT JOIN. - Ambiguous column names. If two tables share a column name, write
table.column. - Putting a filter on the right table in
WHEREafter aLEFT JOINand accidentally turning it back into an inner join (rows withNULLfail most tests).
Key takeaways
JOIN ... ONrebuilds related data by matching a foreign key to a primary key.- Aliases keep joins short; chain
JOINs for more tables. LEFT JOINkeeps unmatched left rows;IS NULLthen finds rows with no match.- Joins work with
WHERE,GROUP BYandORDER BY. - Never join without a condition.
Practice
1. Which column links the first table of lesson section 2 to the second one?
Show answer
orders.customer_id is a foreign key to customers.customer_id.
Show answer
accounts.customer_id is a foreign key to customers.customer_id.
Show answer
sections.course_id is a foreign key to courses.course_id.
2. Write a query listing each row of a linking table with a readable name from the table it points to.
Show answer
SELECT oi.order_id, p.name FROM order_items oi JOIN products p ON oi.product_id = p.product_id; lists each order line with the product name.
Show answer
SELECT k.card_id, a.account_type FROM cards k JOIN accounts a ON k.account_id = a.account_id; lists each card with the type of its account.
Show answer
SELECT e.student_id, sec.term FROM enrollments e JOIN sections sec ON e.section_id = sec.section_id; lists each enrollment with the term of its section.
3. Why does a row without a partner vanish from an inner join?
Show answer
No row on the other side makes the ON condition true for it, so there is no pair to keep.
4. How do you find the rows that have no match?
Show answer
SELECT p.name FROM products p LEFT JOIN order_items i ON i.product_id = p.product_id WHERE i.order_id IS NULL; lists products that were never ordered. In this data every product has been ordered at least once, so it returns no rows.
Show answer
SELECT a.account_id FROM accounts a LEFT JOIN loans l ON l.customer_id = a.customer_id WHERE l.loan_id IS NULL; lists the accounts of customers without a loan.
Show answer
SELECT t.name FROM teachers t LEFT JOIN sections s ON s.teacher_id = t.teacher_id WHERE s.section_id IS NULL; lists teachers who teach no section.
5. What happens if you join two tables with no ON condition?
Show answer
Every row of one table is paired with every row of the other (rows of the first times rows of the second).
6. Why do we split data into tables and join, instead of keeping one wide table?
Show answer
Each fact is stored once (a name is not repeated in every row that refers to it), which saves space and avoids contradictions (chapter 5).
7. Which join keeps every row of both tables, with NULL where there is no partner?
Show answer
A FULL JOIN (in systems that support it; a LEFT JOIN united with a RIGHT JOIN gives the same result).
8. In a self join, why is a.id < b.id added?
Show answer
Without it every row matches itself, and every pair appears twice (A-B and B-A). The condition keeps one row per pair.