Can you join more than two tables?
Yes, you can - SQL allows joining any number of tables in a single query.
The important part is defining the relations between them correctly with JOIN and ON.
The principle
Each new JOIN simply adds one more table onto the already-joined data.
SQL processes them sequentially, like a chain.
Example
Say we have three tables:
usersordersproducts
SELECT
users.name,
orders.order_date,
products.title,
products.price
FROM users
JOIN orders ON users.id = orders.user_id
JOIN products ON orders.product_id = products.id;What happens:
usersgets joined toordersonuser_id,- then that result gets joined to
productsonproduct_id. The result is a table of: user - order - product.
You can join 4, 5, or even 10 tables
FROM A
JOIN B ON ...
JOIN C ON ...
JOIN D ON ...SQL processes them in order, one step at a time.
Important
-
Each join needs a clear
ONcondition, to avoid duplication (an accidental cross join). -
It's better to give tables aliases (short names), which makes the query easier to read:
sqlFROM users u JOIN orders o ON u.id = o.user_id JOIN products p ON o.product_id = p.id
Summary: Yes, you can join an unlimited number of tables. The important part is specifying exactly how they relate to each other, so the result is logical and correct.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.