SQL JOIN: combine two tables
Data is split across tables. JOIN puts the matching rows side by side.
SQL skills · Joins
What you will learn
An invoices table stores a customer_id; the customers table stores the name and region for each customer_id. JOIN connects them.
ON says which columns must match, usually the ID both tables share.
The basics
Real data is split across tables. An invoices table stores a customer_id, and the customers table stores the name and region for each customer_id. JOIN puts them side by side.
SELECT customers.customer_name, invoices.amount
FROM invoices
JOIN customers ON invoices.customer_id = customers.customer_idON says which columns must be equal. Usually that is the ID that both tables share.
Aliases
SELECT c.customer_name, i.amount
FROM invoices i
JOIN customers c ON i.customer_id = c.customer_idShort table names save typing. When a column exists in both tables, like customer_id, you must say which table it comes from.
Which rows?
JOIN, also written INNER JOIN, keeps only rows that have a match on both sides. A customer with five invoices appears five times.
Worked examples
Example 1
Customer name next to each invoice amount.
SELECT c.customer_name, i.amount
FROM invoices i
JOIN customers c ON i.customer_id = c.customer_idAliases i and c keep the query short.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Joining on the wrong IDs, such as invoice_id = customer_id.
- Leaving out the table name for a column that exists in both tables.
- Forgetting that JOIN drops rows without a match.
Where you will use it at work
- Finance: invoices with customer names and regions.
- Sales: deals with the rep’s name and region.
- Support: tickets with the agent’s team.
Questions people ask
Is JOIN the same as INNER JOIN?
Yes. INNER is optional.
Why do I get more rows than in the first table?
Each row appears once for every match. A customer with five invoices appears five times.
Can I join more than two tables?
Yes, add another JOIN ... ON line for each table.
Ready to write it yourself?
Practice JOIN two tables