Write an INNER JOIN
SELECT o.id, c.name, o.total
FROM orders o
JOIN customers c ON o.customer_id = c.id;
The ON clause says which columns must match. An inner join keeps only the rows where a customer exists for the order, dropping any unmatched rows.
Keep unmatched rows with LEFT JOIN
SELECT c.name, o.id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;
A LEFT JOIN returns every customer, even those with no orders. Where there is no match, the order columns come back as NULL.
Join more than two tables
SELECT o.id, c.name, p.title
FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN products p ON o.product_id = p.id;
Chain additional JOIN ... ON clauses to bring in as many related tables as you need.
Common mistakes / tips
- Forgetting ON. Without it you get a cross join that multiplies every row against every other.
- Ambiguous columns. When both tables share a column name, prefix it with the table alias, like
o.id. - Wrong join type. Use LEFT JOIN when you need rows that may have no match.
Frequently asked questions
What is the difference between INNER and LEFT JOIN?
An INNER JOIN returns only rows with a match in both tables. A LEFT JOIN returns all rows from the left table and fills missing right-side values with NULL.
Can I join a table to itself?
Yes. Use two different aliases for the same table, such as employees e JOIN employees m ON e.manager_id = m.id, to relate rows within one table.
Want to practise joins on real tables? Our free SQL course has a live, in-browser query runner.