Joining Three Or More Tables In Sql in SQL
Joining Three or More Tables in SQL
You can join multiple tables by chaining multiple JOIN clauses together, each with its own ON condition.
Syntax:
SELECT columnsFROM table1JOIN table2 ON table1.common_column = table2.common_columnJOIN table3 ON table2.common_column = table3.common_column-- Add more JOINs as needed;Example:
Suppose you have three tables:
Employees
| employee_id | name | department_id |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
| 3 | Charlie | 30 |
Departments
| department_id | department_name |
|---|---|
| 10 | Sales |
| 20 | Marketing |
| 30 | IT |
Salaries
| employee_id | salary |
|---|---|
| 1 | 50000 |
| 2 | 60000 |
| 3 | 70000 |
Query: Join Employees, Departments, and Salaries
SELECT e.name, d.department_name, s.salaryFROM Employees eINNER JOIN Departments d ON e.department_id = d.department_idINNER JOIN Salaries s ON e.employee_id = s.employee_id;Result:
| name | department_name | salary |
|---|---|---|
| Alice | Sales | 50000 |
| Bob | Marketing | 60000 |
| Charlie | IT | 70000 |
Explanation:
First join
EmployeeswithDepartmentsondepartment_id.Then join that result with
Salariesonemployee_id.Returns employee names, their departments, and salaries.
If you want me to explain other join types or more complex queries, just ask!