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:
EmployeeID2 (Bob) is matched withDepartmentID1 (HR). - Row 2:
DepartmentID2 (IT) has no matchingEmployeeIDin theEmployeestable, soEmployeeIDandEmployeeNameare NULL. - Row 3:
EmployeeID3 (Charlie) is matched withDepartmentID3 (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.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
