🔗 Lesson 5: SQL JOINS (Combining Tables)
⏱️ Estimated time: 30 minutes | Difficulty: Intermediate
Data Relationships
In a relational database, data is often spread across multiple tables. JOIN
clauses are used to combine rows from two or more tables, based on a related column between them.
Why Joins?
Data is split across tables. Joins combine related data from multiple tables into one result.
Sample Tables
-- users: id | name | email
-- orders: id | user_id | product | amount
INNER JOIN (Most Common)
Returns only rows that match in both tables.
SELECT users.name, orders.product, orders.amount
FROM users
INNER JOIN orders ON users.id = orders.user_id;
LEFT JOIN
Returns all rows from left table + matching rows from right. NULL if no match.
SELECT users.name, orders.product
FROM users
LEFT JOIN orders ON users.id = orders.user_id;
-- Shows ALL users, even those with no orders
RIGHT JOIN & FULL JOIN
-- RIGHT JOIN: all rows from right table
SELECT * FROM users RIGHT JOIN orders ON users.id = orders.user_id;
-- FULL JOIN: all rows from both tables
SELECT * FROM users FULL JOIN orders ON users.id = orders.user_id;
Table Aliases
SELECT u.name, o.product, o.amount
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.amount > 100;
✅ Quick Quiz
❓ What does INNER JOIN return?
❓ What does LEFT JOIN do when no match exists?
❓ What keyword connects two tables?