1 Introduction to Joins
TopIn a relational database, data is split across multiple tables to avoid duplication. Customer info lives in customers, order info in orders. A JOIN combines rows from two or more tables based on a related column between them.
Without JOINs, you'd have to query each table separately and merge the results in your application code. JOINs let the database do this for you — faster, simpler, and in a single query.
The Key Concept: The ON Clause
Every JOIN needs a condition that tells the database how the tables are related. This is the ON clause:
SELECT customers.name, orders.product, orders.amount
FROM customers
JOIN orders ON customers.id = orders.customer_id;The ON customers.id = orders.customer_id part says: "Match each customer with their orders by connecting the customer's id to the order's customer_id."
Table Aliases: Keep It Clean
Typing full table names gets tedious. Use aliases:
-- c = customers, o = orders
SELECT c.name, o.product, o.amount
FROM customers c
JOIN orders o ON c.id = o.customer_id;Quick Reference: Join Types
| Join Type | Returns | Use When |
|---|---|---|
| INNER JOIN | Only matching rows from both tables | You only want records that exist in both tables |
| LEFT JOIN | All rows from left table + matches from right | You want all customers, even those with no orders |
| RIGHT JOIN | All rows from right table + matches from left | You want all orders, even unassigned ones |
| FULL OUTER JOIN | All rows from both tables | You want everything, matched or not |
| CROSS JOIN | Every row from A paired with every row from B | Generate all possible combinations |
| SELF JOIN | A table joined to itself | Hierarchies (manager/employee), comparisons |
Key Takeaways
- JOINs combine rows from multiple tables based on a related column
- The
ONclause defines how the tables are connected - Use table aliases (
c,o) to keep queries readable - Different JOIN types control what happens with non-matching rows