Skip to main content

Right Join in MySQL

In this tutorial, you will learn about the RIGHT JOIN operation in MySQL. This operation is one of the several types of join operations that you can use to combine rows from two or more tables based on a related column.

What is Right Join in MySQL?

The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from the left table (table1). The result is NULL from the left side when there is no match.

Let's consider the following two tables:

Table1: Employees

EmployeeIDEmployeeNameDepartmentID
1John100
2Robert200
3Michael300

Table2: Departments

DepartmentIDDepartmentName
100HR
200IT
300Finance
400Marketing

The Syntax for RIGHT JOIN

The basic syntax for RIGHT JOIN in MySQL is as follows:

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

How to Use RIGHT JOIN in MySQL

Let's say we want to list all departments and any employees in them. Here's how we would do it:

SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

This would result in the following:

EmployeeNameDepartmentName
JohnHR
RobertIT
MichaelFinance
NULLMarketing

As you can see, the RIGHT JOIN keyword returned all records from the Departments table, and the matched records from the Employees table. The Marketing department did not have any employees, so it returned NULL in the EmployeeName field.

Conclusion

The RIGHT JOIN keyword in MySQL is a very useful operation that you can use to combine rows from two or more tables based on a related column between them. It returns all the records from the right table, and the matched records from the left table. If there is no match, the result is NULL on the left side.

Now that you've learned how to use the RIGHT JOIN in MySQL, try to use it in your queries and see how it can help you retrieve data more efficiently. Happy querying!