Joins: Connecting Tables
Joins: Connecting Tables
Why Joins Exist
Relational design spreads facts across tables: customers in one table, orders in another. To answer a question that touches both, you join them on a shared key. A join combines rows from two tables based on a condition, most often equality between a foreign key and the primary key it references.
SELECT customers.name, orders.total
FROM customers
JOIN orders ON orders.customer_id = customers.id;
Here JOIN (the same as INNER JOIN) keeps only rows where the condition matches, so orders with a missing customer disappear from the result.
Common Join Types
MySQL provides four joins worth learning.
- INNER JOIN keeps only matching rows from both tables.
- LEFT JOIN keeps all rows from the left table and matching rows from the right, using NULL where none exist.
- RIGHT JOIN is the mirror image of LEFT JOIN, keeping all right-table rows.
- CROSS JOIN pairs every row of one table with every row of the other.
LEFT JOIN is the one beginners most often need beyond INNER JOIN, because it answers questions such as which customers have no orders.
SELECT customers.name
FROM customers
LEFT JOIN orders ON orders.customer_id = customers.id
WHERE orders.id IS NULL;
Aliases Keep Queries Readable
Table aliases shorten names and clarify which column comes from which table. Here c and o are aliases, and you can also alias columns to rename them in the output.
SELECT c.name AS customer, o.total AS order_total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;
Joining Many Tables
Joins chain: to list the customers who bought a specific product, connect customers to orders, then orders to order_items, then items to products. Each hop uses the relationship keys designed earlier, which is exactly why clean design makes powerful queries possible.
Key Points
- Joins combine tables on a key, typically a foreign key matching a primary key.
- INNER JOIN keeps matches; LEFT JOIN also keeps unmatched left rows as NULL.
- Aliases shorten table names, and AS renames output columns.
- A missing-match question usually means LEFT JOIN plus a NULL check.
- Chain joins through relationship keys to query several tables at once.