Overview: The RIGHT JOIN is a type of join operation in SQL that retrieves all records from the right table and the matched records from the left table. It combines rows from both tables based on a related column between them.
Syntax:
sqlSELECT column_list
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
Explanation: In the syntax above:
table1
andtable2
are the names of the tables to be joined.column_list
represents the columns to be retrieved from the joined tables.ON
specifies the condition for joining the tables based on a common column.
When the RIGHT JOIN is used, the result set contains all records from the right table and only the matching records from the left table. If there is no match, NULL values are returned for the columns from the left table.
Example:
Consider the following two tables: Employees
and Departments
.
Employees:
EmployeeID | FirstName | LastName | DepartmentID |
---|---|---|---|
1 | John | Smith | 1 |
2 | Jane | Doe | 2 |
3 | David | Johnson | 1 |
4 | Lisa | Brown | 3 |
Departments:
DepartmentID | DepartmentName |
---|---|
1 | Sales |
2 | Marketing |
3 | Finance |
To retrieve all employees and their corresponding department names, you can use a RIGHT JOIN as follows:
sqlSELECT Employees.EmployeeID, Employees.FirstName, Employees.LastName, Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;
Output:
EmployeeID | FirstName | LastName | DepartmentName |
---|---|---|---|
1 | John | Smith | Sales |
2 | Jane | Doe | Marketing |
3 | David | Johnson | Sales |
NULL | NULL | NULL | Finance |
In the result set, you can observe that all the employees are included, and the department name is displayed for each employee. However, since the Finance department does not have any associated employees, NULL values are shown for the columns from the Employees table.
0 Comments