Join Three or More Tables in SQL
To join three or more tables, simply repeat the JOIN clause repeatedly. See the syntax below, where INNER JOIN clause is used to join three tables. Any other JOIN type can be used in the same way. Similarly, it can be used to join any number of tables.
Syntax
The syntax for joining three tables using INNER JOIN keyword is given below:
SELECT table1.column1, table1.column2, ... table2.column1, table2.column2, ... table3.column1, table3.column2, ... FROM table1 INNER JOIN table2 ON table1.matching_column = table2.matching_column INNER JOIN table3 ON table1.matching_column = table3.matching_column;
Example:
Consider a database containing tables called Employee, Bonus_Paid and Contact_Info with the following records:
Table 1: Employee table
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | New York | 24 | 2750 |
3 | Jo | Paris | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Beijing | 28 | 2800 |
Table 2: Bonus_Paid table
EmpID | Bonus |
---|---|
1 | 500 |
2 | 400 |
3 | 450 |
4 | 550 |
5 | 400 |
6 | 600 |
Table 3: Contact_Info table
Phone_Number | EmpID | Address | Gender |
---|---|---|---|
+1-8054098000 | 2 | Brooklyn, New York, USA | F |
+33-147996101 | 3 | Grenelle, Paris, France | M |
+31-201150319 | 4 | Geuzenveld, Amsterdam, Netherlands | F |
+86-1099732458 | 6 | Yizhuangzhen, Beijing, China | M |
+65-67234824 | 7 | Yishun, Singapore | M |
+81-357799072 | 8 | Koto City, Tokyo, Japan | M |
-
To fetch a record containing EmpID, Name, Bonus and Address from these tables, the following SQL query can be used:
SELECT Employee.EmpID, Employee.Name, Bonus_Paid.Bonus, Contact_Info.Address FROM Employee INNER JOIN Bonus_Paid ON Employee.EmpID = Bonus_Paid.EmpID INNER JOIN Contact_Info ON Employee.EmpID = Contact_Info.EmpID;
This will produce the result as shown below:
EmpID Name Bonus Address 2 Marry 400 Brooklyn, New York, USA 3 Jo 450 Grenelle, Paris, France 4 Kim 550 Geuzenveld, Amsterdam, Netherlands 6 Huang 600 Yizhuangzhen, Beijing, China -
To fetch the above record but with a condition like Bonus should be greater than equal to 500, the following SQL query can be used:
SELECT Employee.EmpID, Employee.Name, Bonus_Paid.Bonus, Contact_Info.Gender, Contact_Info.Address FROM Employee INNER JOIN Bonus_Paid ON Employee.EmpID = Bonus_Paid.EmpID INNER JOIN Contact_Info ON Employee.EmpID = Contact_Info.EmpID WHERE Bonus_Paid.Bonus >= 500;
This result of the following code will be:
EmpID Name Bonus Address 4 Kim 550 Geuzenveld, Amsterdam, Netherlands 6 Huang 600 Yizhuangzhen, Beijing, China