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
EmployeeID | EmployeeName | DepartmentID |
---|---|---|
1 | John | 100 |
2 | Robert | 200 |
3 | Michael | 300 |
Table2: Departments
DepartmentID | DepartmentName |
---|---|
100 | HR |
200 | IT |
300 | Finance |
400 | Marketing |
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:
EmployeeName | DepartmentName |
---|---|
John | HR |
Robert | IT |
Michael | Finance |
NULL | Marketing |
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!