In MySQL, the RIGHT JOIN keyword is used to retrieve all records from the right table (table2), and the matched records from the left table (table1). The result is NULL from the left side if there is no match.
Here's the basic syntax of the RIGHT JOIN:
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Let's say we have two tables: employees and departments. The employees table contains information about employees, including their department ID, and the departments table contains department names and their corresponding department IDs.
We want to retrieve the names of all departments along with the names of the employees who belong to each department. If a department does not have any employees, we still want to include its information in the result set, with the employee names as NULL.
SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;
In this query:
RIGHT JOIN is less commonly used compared to LEFT JOIN, but it serves a similar purpose. It ensures that all records from the right table are included in the result set, even if there are no matches in the left table.