Relational databases use JOIN operations to combine data from different tables for analysis. DB2, a popular database management system, offers powerful JOIN functionalities. In this blog post, we will explore the types, syntax, and examples of DB2 JOIN operations. By the end, you will have the knowledge to effectively use JOINs in DB2 for data retrieval and analysis.

DB2 Join SQL Query
Photo by Teona Swift on Pexels.com

Join in DB2

In this article, we will cover:

  • Understanding the fundamentals of JOIN operations in DB2.
  • Examining practical scenarios using SQL query to perform JOIN operations with step-by-step explanations.

Here are two tables. Employees” and “Departments”. Then run the JOIN SQL query to retrieve the required information.

Employees Table:

EmployeeIDFirstNameLastNameDepartmentID
1JohnDoe101
2JaneSmith102
3RobertJohnson101
4EmilyBrown103
5MichaelLee102
Table 1

Departments Table:

DepartmentIDDepartmentNameManagerID
101HR1
102IT2
103Finance4
Table 2

Join SQL Query

SELECT e.EmployeeID, e.FirstName, e.LastName, d.DepartmentName, m.FirstName AS ManagerFirstName, m.LastName AS ManagerLastName 
FROM Employees e 
JOIN Departments d 
ON e.DepartmentID = d.DepartmentID 
JOIN Employees m ON d.ManagerID = m.EmployeeID;

Result:

EmployeeIDFirstNameLastNameDepartmentNameManagerFirstNameManagerLastName
1JohnDoeHRJohnDoe
2JaneSmithITJaneSmith
3RobertJohnsonHRJohnDoe
4EmilyBrownFinanceEmilyBrown
5MichaelLeeITJaneSmith
Result

In the above query, we used JOIN operations to connect the “Employees” and “Departments” tables twice. The first JOIN connects the tables based on the “DepartmentID” column, and the second JOIN connects the tables based on the “ManagerID” and “EmployeeID” columns to retrieve the names of the department managers.

As a result, we get a list of all employees with their respective department names and the names of their department managers.

Related