SQL RIGHT JOIN
A SQL RIGHT JOIN (or RIGHT OUTER JOIN) returns all rows from the right table, and the matched rows from the left table. If there is no match, the result is NULL on the side of the left table.
Syntax
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
Example
Let's consider two tables:
Employees
| EmployeeID |
EmployeeName |
| 1 |
Alice |
| 2 |
Bob |
| 3 |
Charlie |
Departments
| DepartmentID |
DepartmentName |
EmployeeID |
| 1 |
HR |
2 |
| 2 |
IT |
4 |
| 3 |
Finance |
3 |
RIGHT JOIN Query
SELECT Employees.EmployeeID, Employees.EmployeeName, Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments
ON Employees.EmployeeID = Departments.EmployeeID;
Output
| EmployeeID |
EmployeeName |
DepartmentName |
| 2 |
Bob |
HR |
| NULL |
NULL |
IT |
| 3 |
Charlie |
Finance |
Explanation
- Row 1:
EmployeeID 2 (Bob) is matched with DepartmentID 1 (HR).
- Row 2:
DepartmentID 2 (IT) has no matching EmployeeID in the Employees table, so EmployeeID and EmployeeName are NULL.
- Row 3:
EmployeeID 3 (Charlie) is matched with DepartmentID 3 (Finance).
In this example, all departments are listed because of the RIGHT JOIN, even if no employee is assigned to a department, as seen in the row for the IT department.