Table aliases
- SQL course
- Beginner
- Lesson 104/115
- 4 min
Give a table a short name in FROM and JOIN.
Multi-table JOIN
You can join many tables with successive JOINs. Each JOIN gets its own ON condition.
SELECT o.id, c.name, p.name
FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN products p ON o.product_id = p.id;This query combines order, customer and product in one query.
o.id, c.name, p.name is selected from orders o. customers c is joined on o.customer_id = c.id, keeping only matching rows. products p is joined on o.product_id = p.id, keeping only matching rows.
Multi-table JOIN — details
Each JOIN merges the previous result with a new table. In multi-table queries aliases are almost mandatory.
Practice Multi-table JOIN
Join orders, customers and products on customer_id and product_id.
Starter code
-- join three tables
SELECT o.id, c.name, p.name
FROM orders o
JOINSample solution
SELECT o.id, c.name, p.name
FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN products p ON o.product_id = p.idExpected output
id name name 1 Ayşe Kalem 2 Alex Defter
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does each JOIN need in a multi-join?
- A shared WHERE
- A single FROM
- Its own ON condition Correct answer
- GROUP BY
Explanation: Each JOIN gets its own ON.
2 Three tables
FROM orders o
JOIN customers c ON o.customer_id = c.id
____ products p ON o.product_id = p.id;
FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN products p ON o.product_id = p.id;
Explanation: To add a third table you write another JOIN with its own ON condition.
3 Table aliases: match the terms
| Term | Meaning |
|---|---|
JOIN |
join |
ON |
condition |
alias |
short name |
FROM |
table |