SQL Server Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

SQL Right Join

Back to: SQL Server Tutorial

In SQL, a RIGHT JOIN (or RIGHT OUTER JOIN) is used to combine rows from two tables based on a related column between them, but it ensures that all rows from the right table are included in the result set. If there is no matching row in the left table, the result set will still include the rows from the right table, with NULL values for columns from the left table.

Here's the basic syntax for a RIGHT JOIN:

SELECT columns FROM left_table RIGHT JOIN right_table ON left_table.common_column = right_table.common_column;

Example Scenario

Assume you have two tables: employees and departments.

employees table:

employee_id name department_id
1 Alice 10
2 Bob 20
3 Charlie 30

departments table:

department_id department_name
10 HR
20 IT
30 Finance
40 Marketing

You want to list all departments and the employees in those departments, but you want to ensure that all departments are listed even if there are no employees in some departments.

Here’s how you can use a RIGHT JOIN to achieve this:

SELECT d.department_id, d.department_name, e.name FROM employees e RIGHT JOIN departments d ON e.department_id = d.department_id;

Result

The result of the query will include all departments, and if there are employees in those departments, their names will be shown. If a department has no employees, the employee name will be NULL.

department_id department_name name
10 HR Alice
20 IT Bob
30 Finance Charlie
40 Marketing NULL

In this result:

  • The HR, IT, and Finance departments have corresponding employees.
  • The Marketing department does not have any employees, so the name column shows NULL.

Using a RIGHT JOIN ensures that all rows from the right table (departments) are included in the result, with matching rows from the left table (employees) where available.

Scroll to Top