The basic syntax of a RIGHT JOIN
is:
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
table1
, table2
: The two tables to join.column
: The column(s) used to match rows in both tables.Let’s assume we have two tables: employees
and departments
. We want to retrieve all departments and their corresponding employee names. If a department has no employees, the employee name will show as NULL
. Here’s the query:
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id;
In this example:
departments
table.department_id
from the employees
table with the id
in the departments
table.NULL
for columns from the left table.The RIGHT JOIN
is useful when you need to include all records from the right table, even if there are no matching records in the left table. It ensures that no data from the right table is excluded, with NULL
values for missing data from the left table. Using RIGHT JOIN
helps in cases where you want to focus on the right table while still considering matching data from the left table.