3. Joins: combine tables
3.1 INNER JOIN: match rows from two tables
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Real data is split across tables. orders stores a customer_id, not the customer's name. A join brings the matching rows together.
JOIN customers AS c→ the second table, with a short namecON o.customer_id = c.id→ the rule that says which rows matcho.product,c.name→ the short name tells which table a column comes from
JOIN on its own means INNER JOIN: a row appears only when it has a match in both tables.
pandas vs SQL
orders.merge(customers, left_on="customer_id", right_on="id")
is the same as
FROM orders AS o JOIN customers AS c ON o.customer_id = c.id
Never forget ON. Without it, every order is paired with every customer: 8 × 5 = 40 rows here, and billions on real tables.
How it fits together
- orders (customer_id)
- ON customer_id = id
- Order + customer name
Watch the query run
SQL
SELECT o.id, c.name, o.productFROM orders AS oJOIN customers AS c ON o.customer_id = c.idWHERE o.amount > 10000ORDER BY o.id;
Rows at this step
id | name | product ----+-------+-------- 101 | Asha | Laptop 104 | Meera | Monitor 105 | Ravi | Laptop 107 | Asha | Monitor
Practice in SQL ✓ Solved
For orders with status pending, show the order id and the customer's city. Sort by id.
Tables you can query: customers, orders
customers id | name | city ---+-------+------ 1 | Asha | Noida 2 | Ravi | Delhi 3 | Meera | Pune 4 | Kabir | Noida 5 | Zoya | NULL orders id | customer_id | product | amount | status | order_date ----+-------------+----------+--------+-----------+----------- 101 | 1 | Laptop | 55000 | delivered | 2026-01-05 102 | 2 | Mouse | 700 | delivered | 2026-01-06 103 | 1 | Keyboard | 1500 | delivered | 2026-01-09 104 | 3 | Monitor | 12000 | cancelled | 2026-01-12 105 | 2 | Laptop | 52000 | delivered | 2026-01-15 106 | 4 | Mouse | 650 | pending | 2026-01-18 107 | 1 | Monitor | 11500 | delivered | 2026-01-20 108 | 3 | Keyboard | NULL | pending | 2026-01-22
Expected output
id | city ----+------ 106 | Noida 108 | Pune
Reference solution
SELECT o.id, c.city
FROM orders AS o
JOIN customers AS c
ON o.customer_id = c.id
WHERE o.status = 'pending'
ORDER BY o.id;
Question 1 · Easy
What does ON do in a join?
Question 2 · Medium
Zoya has no orders. Does she appear in orders JOIN customers?
Question 3 · Hard
orders has 8 rows and customers has 5. You forget ON. How many rows come back?
Key takeaways
A join combines tables. ON gives the matching rule. An inner join keeps only rows that match in both tables.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in