INNER JOIN
Combine two tables into one result with INNER JOIN, and see which rows find a partner and which quietly disappear.
A join glues rows from two tables
Data lives in separate tables so nothing is stored twice. A join builds one wider table out of two by pairing up rows. You tell the database how to pair them with an ON test.
INNER JOIN keeps a pair only when the ON test is true. A row that finds no partner is left out. INNER is the default, so a plain JOIN means the same thing.
Answers live across tables
A question like "which customer bought a Notebook?" needs the customer name from one table and the item from another. A join is how one query reads both.
Match customers to their orders
SELECT c.name, o.item
FROM customers AS c
INNER JOIN orders AS o
ON c.id = o.customer_id;c and o are short names (aliases) for the two tables. The ON test says a customer matches an order when the customer's id equals the order's customer_id.
Asha has two orders, so she appears twice. Ben has one. Chen, Dara and Eli have no orders, so they find no partner and do not appear at all.
Match and mismatch
Switch the ON test to the wrong key and watch the result empty out. Then add the Pune filter and see how WHERE trims the joined rows.
| idinteger | nametext | citytext |
|---|---|---|
| 1 | Asha | Pune |
| 2 | Ben | Leeds |
| 3 | Chen | Oslo |
| 4 | Dara | Lima |
| 5 | Eli | Rome |
| idinteger | customer_idinteger | itemtext |
|---|---|---|
| 101 | 1 | Notebook |
| 102 | 1 | Pen |
| 103 | 2 | Ruler |
| nametext | itemtext |
|---|---|
| Asha | Notebook |
| Asha | Pen |
| Ben | Ruler |
INNER JOIN keeps a pair only when the ON test is true. Asha has two orders, so she appears twice. Chen, Dara and Eli have no orders, so they do not appear.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A join pairs rows from two tables using an ON test, and INNER JOIN keeps only the pairs where ON is true.
- A row with no partner is dropped without any error.
- A row with several partners appears once for each partner.
- A NULL key never matches, so rows with a NULL key do not survive an INNER JOIN.
Done with this concept?
Mark it complete to track your progress. No login needed.