JOIN: Combining Tables
Data is split across tables to avoid repeating it. An order stores only customer_id, not the customer's name. A JOIN puts them back together using the matching columns.
Good databases don't repeat data: a customer's name is stored once in a customers table, and orders just refer to the customer's id. JOIN brings the related rows back together when you need them, like "show each order with the customer's name". Joins are the most important skill in SQL after SELECT.
INNER JOIN - only matching rows
Example
SELECT o.id AS order_id, c.name, o.order_date, o.status
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY o.id;
-- Result:
-- order_id | name | order_date | status
-- ---------+-------------+------------+----------
-- 101 | Asha Verma | 2026-10-02 | delivered
-- 102 | Ravi Kumar | 2026-10-05 | delivered
-- 103 | Asha Verma | 2026-10-18 | shipped
-- 104 | Neha Singh | 2026-10-20 | cancelled
-- 105 | Arjun Mehta | 2026-11-01 | delivered
-- 106 | Fatima Khan | 2026-11-03 | placed
-- 107 | Ravi Kumar | 2026-11-10 | shipped
-- 108 | Asha Verma | 2026-11-15 | placed▶ Try it yourselfo and c are short aliases for the table names.
LEFT JOIN - keep everything on the left
A LEFT JOIN keeps every row of the first table, even with no match. Missing values become NULL. This finds customers who never ordered:
Example
SELECT c.name, o.id AS order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
-- Result:
-- name | order_id
-- -----------+---------
-- Vikram Rao | NULL▶ Try it yourselfJoining three tables
Example
SELECT o.id AS order_id, p.name AS product, oi.qty, oi.qty * oi.price AS amount
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
WHERE o.customer_id = 1
ORDER BY o.id;
-- Result:
-- order_id | product | qty | amount
-- ---------+--------------------+-----+-------
-- 101 | Cotton T-shirt | 2 | 998
-- 101 | Notebook Pack | 3 | 597
-- 103 | Denim Jeans | 1 | 1299
-- 103 | Steel Water Bottle | 2 | 698
-- 108 | Python Book | 1 | 599▶ Try it yourselfRIGHT JOIN keeps all rows of the second table, and FULL OUTER JOIN keeps all rows of both. LEFT JOIN is by far the most used - you can always swap the table order.Key points
- JOIN combines rows from tables using a related column.
- INNER JOIN keeps matches; LEFT JOIN keeps all rows from the left table.
- Use table aliases to keep queries readable.
📝 Test yourself
1. Which join keeps customers with no orders?
2. What does ON c.id = o.customer_id say?
3. Fill in the join that only keeps matching rows:
SELECT * FROM orders JOIN customers ON ...
