(because real-world stuff lives in more than one place)
👀 Picture This…
You’ve got two tables:
🧑 users
table:
user_id | name |
---|---|
1 | Olivia |
2 | Mason |
3 | Zoe |
📦 orders
table:
order_id | user_id | product |
---|---|---|
101 | 1 | Laptop |
102 | 1 | Headphones |
103 | 2 | Phone |
Now the question is:
“What did each user buy?”
But that info is split across two tables.
That’s where JOIN comes in.
🔧 Basic Syntax (INNER JOIN)
SELECT users.name, orders.product
FROM users
JOIN orders
ON users.user_id = orders.user_id;
You’re telling SQL:
“Hey, connect these two tables where their user_id
matches.”
✅ Result:
name | product |
---|---|
Olivia | Laptop |
Olivia | Headphones |
Mason | Phone |
🔁 Types of JOINS (The Quick Guide)
Type | What it shows |
---|---|
INNER JOIN | Only matched rows from both tables |
LEFT JOIN | All rows from the left table + matches from the right |
RIGHT JOIN | All rows from the right table + matches from the left |
FULL JOIN | All rows from both tables (if supported) |
🧪 Example: LEFT JOIN
Let’s see all users, even if they haven’t ordered anything yet:
SELECT users.name, orders.product
FROM users
LEFT JOIN orders
ON users.user_id = orders.user_id;
✅ Result:
name | product |
---|---|
Olivia | Laptop |
Olivia | Headphones |
Mason | Phone |
Zoe | NULL |
LEFT JOIN keeps everyone from users
, even if there’s nothing in orders
.
🧃 Recap
- Use
JOIN
to combine related data across tables ON
links them through matching columns (likeuser_id
)INNER JOIN
= only matched rowsLEFT JOIN
= keep all from the left- JOINs let you answer real questions, like “who bought what?”