The INNER JOIN: Connecting Matching Records 🤝
In Chapter 1, we learned why professional databases split data across multiple normalized tables using Primary Keys and Foreign Keys: it eliminates duplication and prevents data corruption.
However, when generating reports or building user interfaces, you frequently need to stitch that data back together:
- "Show me customer names alongside the items they purchased."
- "Display each student's name alongside their enrolled course title."
- "Show every transaction with the account holder's email."
In SQL, this stitching is achieved using JOIN.
The most common, foundational join is the INNER JOIN.
1. Our Practice Dataset: Customers & Orders 📦
Let's look at two simple tables:
Table: customers Table: orders
┌────┬──────────────┬─────────────┐ ┌──────────┬─────────────┬────────┐
│ id │ name │ city │ │ order_id │ customer_id │ amount │
├────┼──────────────┼─────────────┤ ├──────────┼─────────────┼────────┤
│ 1 │ Aarav Sharma │ Pune │ │ 101 │ 1 │ 4500 │
│ 2 │ Rahul Sharma │ Mumbai │ │ 102 │ 1 │ 1200 │
│ 3 │ Priya Patel │ Delhi │ │ 103 │ 2 │ 8900 │
│ 4 │ Amit Verma │ Bengaluru │ │ 104 │ 99 │ 300 │ (Unknown customer!)
└────┴──────────────┴─────────────┘ └──────────┴─────────────┴────────┘
(Notice: Priya & Amit have NO orders!)
2. What Does INNER JOIN Do? 🎯
An
INNER JOINreturns only the rows that have matching values in both tables.
If a row in Table A does not match any row in Table B, it is excluded from the result.
Venn Diagram: INNER JOIN
┌───────────────┐ ┌───────────────┐
│ CUSTOMERS │ │ ORDERS │
│ │ │ │
│ Priya, Amit │ │ │
│ (No orders) │█│█ (Order 104) │
│ │ │ (No customer)│
└───────────────┘ └───────────────┘
▲
Matching Records:
Aarav Sharma (101, 102)
Rahul Sharma (103)
The Basic Syntax:
SELECT customers.name, orders.order_id, orders.amountFROM customersINNER JOIN orders ON customers.id = orders.customer_id;Result:
┌──────────────┬──────────┬────────┐
│ name │ order_id │ amount │
├──────────────┼──────────┼────────┤
│ Aarav Sharma │ 101 │ 4500 │
│ Aarav Sharma │ 102 │ 1200 │
│ Rahul Sharma │ 103 │ 8900 │
└──────────────┴──────────┴────────┘
Notice what happened:
Aarav Sharmaappears twice because she has two matching orders.Rahul Sharmaappears once.PriyaandAmitare omitted because they have placed 0 orders.- Order
104is omitted becausecustomer_id = 99does not exist incustomers.
Syntax Tip: In SQL, writing
JOINby itself defaults to anINNER JOIN. However, writingINNER JOINexplicitly is considered best practice for code readability.
Interactive Venn Diagram Join Explorer 🕹️
Toggle between INNER, LEFT, RIGHT, FULL, and CROSS joins below to see the animated Venn diagram shading and watch the resulting rows change in real time:
Only records with matching keys in BOTH tables survive. Priya (no orders) and Order 104 (unknown customer) are omitted.
| c.name | o.order_id | o.item | Join Match Status |
|---|---|---|---|
| Aarav | 101 | Laptop | Matched (Intersection) |
| Aarav | 102 | Mouse | Matched (Intersection) |
| Rahul | 103 | Keyboard | Matched (Intersection) |
3. Resolving Ambiguity with Table Aliases 🏷️
If both tables have a column with the same name (like id or created_at), writing SELECT id causes an error:ERROR: column reference "id" is ambiguous.
You must qualify the column name with its table prefix: customers.id vs orders.id.
To make queries clean and concise, use short Table Aliases:
SELECT c.name, c.city, o.order_id, o.amountFROM customers AS cINNER JOIN orders AS o ON c.id = o.customer_id;4. Combining JOIN with WHERE, ORDER BY, & Aggregates 🚀
A joined table is just like any other table in SQL! You can filter, sort, group, and aggregate across the joined dataset:
Example 1: Filtering Joined Records
Find high-value orders placed specifically by customers in Pune:
SELECT c.name, c.city, o.order_id, o.amountFROM customers cINNER JOIN orders o ON c.id = o.customer_idWHERE c.city = 'Pune' AND o.amount > 2000ORDER BY o.amount DESC;Example 2: Grouping & Aggregating Across Tables
Calculate the total amount spent by each customer:
SELECT c.name, COUNT(o.order_id) AS total_orders_placed, SUM(o.amount) AS total_spentFROM customers cINNER JOIN orders o ON c.id = o.customer_idGROUP BY c.id, c.nameORDER BY total_spent DESC;5. Multi-Table Joins (Joining 3 or More Tables) 🏗️
In real applications, relationships often span three or more tables:CustomersOrdersOrder_ItemsProducts.
You simply chain additional INNER JOIN ... ON ... clauses:
SELECT c.name AS customer_name, o.order_id, p.product_name, oi.quantity, p.priceFROM customers cINNER JOIN orders o ON c.id = o.customer_idINNER JOIN order_items oi ON o.order_id = oi.order_idINNER JOIN products p ON oi.product_id = p.idWHERE c.city = 'Mumbai';Flashcard Checkpoint 🎴
What happens to rows in Table A that do not find any matching foreign key in Table B during an INNER JOIN?
What causes the 'column reference is ambiguous' error during a JOIN, and how do you fix it?
id). You fix it by prefixing the column with the table name or alias (e.g. c.id or o.id).