0
0
SQLquery~5 mins

Joining more than two tables in SQL

Choose your learning style9 modes available
Introduction
Joining more than two tables lets you combine data from multiple sources to see related information all together.
You want to see customer orders along with product details and shipping info.
You need to get employee info, their department, and their manager's contact in one list.
You want to analyze sales data by joining sales, products, and store locations.
You want to combine student records with their classes and teachers.
You want to create a report that shows invoices, payments, and customer details.
Syntax
SQL
SELECT columns
FROM table1
JOIN table2 ON table1.common_column = table2.common_column
JOIN table3 ON table2.common_column = table3.common_column;
You can join as many tables as you need by adding more JOIN clauses.
Each JOIN needs a condition to tell how the tables relate to each other.
Examples
This joins three tables: orders, customers, and products to show order IDs with customer and product names.
SQL
SELECT orders.id, customers.name, products.name
FROM orders
JOIN customers ON orders.customer_id = customers.id
JOIN products ON orders.product_id = products.id;
This joins employees with their departments and the managers of those departments.
SQL
SELECT employees.name, departments.name, managers.name
FROM employees
JOIN departments ON employees.department_id = departments.id
JOIN managers ON departments.manager_id = managers.id;
Sample Program
This example creates three tables and joins them to list orders with customer and product names.
SQL
CREATE TABLE customers (id INT, name VARCHAR(50));
CREATE TABLE orders (id INT, customer_id INT, product_id INT);
CREATE TABLE products (id INT, name VARCHAR(50));

INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob');
INSERT INTO products VALUES (10, 'Book'), (20, 'Pen');
INSERT INTO orders VALUES (100, 1, 10), (101, 2, 20);

SELECT orders.id AS order_id, customers.name AS customer_name, products.name AS product_name
FROM orders
JOIN customers ON orders.customer_id = customers.id
JOIN products ON orders.product_id = products.id;
OutputSuccess
Important Notes
Always use clear and matching column names in JOIN conditions to avoid confusion.
If tables have columns with the same name, use table aliases or full names to avoid errors.
Joining many tables can slow down queries; only join what you need.
Summary
Joining more than two tables combines data from multiple sources into one result.
Use multiple JOIN clauses with conditions to connect tables step by step.
Check your JOIN conditions carefully to get correct and meaningful results.