Simple Ways to Join Three Tables in SQL
Database management and querying are critical for modern businesses to manage and analyze their data effectively. In this article, we will discuss simple ways to join three tables in SQL (Structured Query Language), which is a standard language used to communicate with various database systems.
Understanding Joins in SQL
In SQL, joins are used to combine data from multiple tables based on a related column between these tables. There are several types of join operations available in SQL like INNER JOIN, OUTER JOIN (LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN), and CROSS JOIN. We will focus on INNER JOIN and OUTER JOIN for this article.
1.Joining Three Tables Using INNER JOIN
INNER JOIN returns records that have matching values in both tables. Let’s consider three sample tables: Employees, Departments and Salaries.
Employees Table:
EmployeeID | FirstName | LastName | DepartmentID
———–+———–+———-+————-
1 | John | Doe | 1
2 | Jane | Smith | 2
Departments Table:
DepartmentID | DepartmentName
————-+—————
1 | HR
2 | Finance
Salaries Table:
EmployeeID | AnnualSalary
———–+————-
1 | 50000
2 | 60000
In order to join these three tables using INNER JOIN, follow the below query:
“`
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName, Salaries.AnnualSalary
FROM Employees
JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
JOIN Salaries ON Employees.EmployeeID = Salaries.EmployeeID;
“`
The result will be:
FirstName | LastName | DepartmentName | AnnualSalary
———-+———-+—————+————-
John | Doe | HR | 50000
Jane | Smith | Finance | 60000
2.Joining Three Tables Using OUTER JOIN (LEFT JOIN)
LEFT JOIN returns all records from the left table (Employees), and the matched records from the right table (Departments and Salaries). If no match is found, NULL values are returned.
Using our previous example, let’s modify our query with a LEFT JOIN:
“`
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName, Salaries.AnnualSalary
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
LEFT JOIN Salaries ON Employees.EmployeeID = Salaries.EmployeeID;
“`
The result will be the same as INNER JOIN since we don’t have any NULL values in this case. However, if there were employees without departments or salaries, they would still be displayed with NULL values in those columns.
Conclusion
In this article, we demonstrated simple ways to join three tables in SQL using INNER JOIN and OUTER JOIN (LEFT JOIN). Joining multiple tables helps consolidate information from various sources, making data analysis more effective and efficient for businesses.