SQL Joins
A JOIN
clause is used to combine rows from two or more tables, based on a related column between them.
assuming we have a sample data:
Example Data
Employees Table
EmployeeID | EmployeeName | DepartmentID |
---|---|---|
1 | John Doe | 1 |
2 | Jane Smith | 2 |
3 | Jim Brown | 3 |
4 |
Jake Blues | NULL |
Departments Table
DepartmentID | DepartmentName |
---|---|
1 | Human Resources |
2 | Marketing |
3 | Engineering |
5 | Sales |
INNER JOIN
Returns records that have matching values in both tables.
From this #Example Data, if we want to find out at least one match in both tables:
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
Expected Result:
EmployeeName | DepartmentName |
---|---|
John Doe | Human Resources |
Jane Smith | Marketing |
Jim Brown | Engineering |
LEFT OUTER JOIN
Returns all records from the left table and the matched records from the right table.
From this #Example Data, if we want to find out all employees and matched rows from the department table.
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
LEFT OUTER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
Expected result:
EmployeeName | DepartmentName |
---|---|
John Doe | Human Resources |
Jane Smith | Marketing |
Jim Brown | Engineering |
Jake Blues | NULL |
RIGHT OUTER JOIN
Returns all records from the right table and the matched records from the left table.
From this #Example Data, if we want to find out all departments and matched rows from the employee table.
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
RIGHT OUTER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
Expected result:
EmployeeName | DepartmentName |
---|---|
John Doe | Human Resources |
Jane Smith | Marketing |
Jim Brown | Engineering |
NULL | Sales |
FULL OUTER JOIN
Returns all records when there is a match in either left or right table.
From this #Example Data, this join returns rows when there is a match in one of the tables. Thus, it shows all records from both tables, with NULL on one side if there is no match.
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
FULL OUTER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
Expected result:
EmployeeName | DepartmentName |
---|---|
John Doe | Human Resources |
Jane Smith | Marketing |
Jim Brown | Engineering |
Jake Blues | NULL |
NULL | Sales |