JOINs: combining tables
Good database design splits data into separate tables so nothing is duplicated: customers in one, products in another, orders linking them. A JOIN puts that data back together in a query.
INNER JOIN
Returns rows where there's a match in both tables.
oandcare table aliases: short names that keep queries readable.ONsays how the rows relate: the order'scustomer_idequals the customer'sid.JOINon its own meansINNER JOIN.
Joining three tables
LEFT JOIN
Returns every row from the left table, plus matching rows from the right. Where there's no match, the right side's columns are NULL.
Notice Fatima has 0 orders. An inner join would have dropped her completely.
Finding rows with no match
A classic pattern: LEFT JOIN … WHERE right.id IS NULL.
Join types at a glance
| Join | Returns |
|---|---|
INNER JOIN |
Only matching rows from both sides |
LEFT JOIN |
All left rows + matches (NULLs where none) |
RIGHT JOIN |
All right rows + matches |
FULL OUTER JOIN |
All rows from both sides |
CROSS JOIN |
Every combination (rows × rows) |
Self join
A table can be joined to itself, for example to find customers from the same city:
Joins + aggregates = reports
Practice
- List each customer's name with the total amount they've spent, highest first.
- Find customers who have never ordered anything.
✎ Check your understanding
1.You want every customer, even those with no orders. Which join?
2.What does ON c.id = o.customer_id do?