🔹 RIGHT JOIN in SQL
Definition:
The RIGHT JOIN
clause returns all records from the right table, and the matched records from the left table. If there is no match, the result is NULL from the left table.
Syntax:
SELECT table1.column, table2.column
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
Example:
SELECT Employees.name, Departments.department_name
FROM Employees
RIGHT JOIN Departments
ON Employees.department_id = Departments.department_id;
Sample Employees
Table:
id | name | department_id |
1 | Alice | 101 |
2 | Bob | 102 |
3 | Charlie | 103 |
Sample Departments
Table:
department_id | department_name |
101 | HR |
102 | Engineering |
104 | Finance |
Output:
name | department_name |
Alice | HR |
Bob | Engineering |
NULL | Finance |
Explanation:
The query returns all rows from the Departments
table:
- HR (101) → Alice
- Engineering (102) → Bob
- Finance (104) → No match in Employees → **NULL**
Charlie (dept 103) has no matching department → **not shown**
RIGHT JOIN ensures every row from the right table appears, matched or not.
Usage Tips:
- Use
RIGHT JOIN
when you want all rows from the second (right) table regardless of matches.
- Useful when the right table is primary, and you want to know which rows aren't linked in the left table.
Common Mistake:
Assuming RIGHT JOIN
excludes unmatched right table rows. It doesn't — unmatched right table rows are included, with NULLs for left table columns.
📘 Note: RIGHT JOIN
is sometimes called RIGHT OUTER JOIN
; both are the same.