RIGHT JOIN

A RIGHT JOIN is used to combine rows from two tables. It returns all rows from the right table and the matched rows from the left table. If there is no match, the result contains NULL for columns from the left table.

Syntax

SELECT column_list
FROM left_table
RIGHT JOIN right_table
ON left_table.column_name = right_table.column_name;
  • left_table: The first table in the query.
  • right_table: The second table. All rows from this table are returned.
  • column_list: Columns you want to retrieve.
  • ON: The condition that specifies how the tables are related.

How RIGHT JOIN Works

  1. SQL starts with the right table.
  2. For each row in the right table, it finds matching rows in the left table based on the ON condition.
  3. If a match exists, the columns from both tables are returned.
  4. If no match exists, columns from the left table are filled with NULL.

Example

Suppose we have two tables:

Employees

EmployeeIDNameDeptID
1Alice10
2Bob20
3Charlie30

Departments

DeptIDDeptName
10HR
20Finance
40IT

Query:

SELECT Employees.Name, Departments.DeptName
FROM Employees
RIGHT JOIN Departments
ON Employees.DeptID = Departments.DeptID;

Result:

NameDeptName
AliceHR
BobFinance
NULLIT

Explanation: The IT department has no matching employee, so Name shows NULL.

Key Points

  • RIGHT JOIN ensures all records from the right table appear in the results.
  • Use RIGHT JOIN when the right table is your main reference and you want all its data, even if the left table has no matches.
  • NULL appears in unmatched columns from the left table.
  • RIGHT JOIN can be rewritten as LEFT JOIN by swapping the table positions.
Home » SQL Foundations Program (SQL-101) > Basic Joins > RIGHT JOIN