In SQL, a RIGHT JOIN
(or RIGHT OUTER JOIN
) is used to combine rows from two tables based on a related column between them, but it ensures that all rows from the right table are included in the result set. If there is no matching row in the left table, the result set will still include the rows from the right table, with NULL
values for columns from the left table.
Here's the basic syntax for a RIGHT JOIN
:
Example Scenario
Assume you have two tables: employees
and departments
.
employees table:
employee_id | name | department_id |
---|---|---|
1 | Alice | 10 |
2 | Bob | 20 |
3 | Charlie | 30 |
departments table:
department_id | department_name |
---|---|
10 | HR |
20 | IT |
30 | Finance |
40 | Marketing |
You want to list all departments and the employees in those departments, but you want to ensure that all departments are listed even if there are no employees in some departments.
Here’s how you can use a RIGHT JOIN
to achieve this:
Result
The result of the query will include all departments, and if there are employees in those departments, their names will be shown. If a department has no employees, the employee name will be NULL
.
department_id | department_name | name |
---|---|---|
10 | HR | Alice |
20 | IT | Bob |
30 | Finance | Charlie |
40 | Marketing | NULL |
In this result:
- The
HR
,IT
, andFinance
departments have corresponding employees. - The
Marketing
department does not have any employees, so thename
column showsNULL
.
Using a RIGHT JOIN
ensures that all rows from the right table (departments
) are included in the result, with matching rows from the left table (employees
) where available.