Thursday, December 19, 2024

SQL RIGHT JOIN Keyword

 The SQL RIGHT JOIN (also known as RIGHT OUTER JOIN) is used to combine rows from two tables based on a related column between them, but it returns all rows from the right table (the second table) and the matching rows from the left table (the first table). If there is no match, the result is NULL for the columns from the left table.

Syntax:

SELECT column1, column2, ...
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;

Explanation:

  • RIGHT JOIN: Ensures that all rows from the second (right) table are returned.
  • table1.column and table2.column: Specifies the columns used to match rows from both tables.
  • If a row from table2 has no corresponding match in table1, the result will contain NULL for the columns of table1.

Example:

Consider two tables:

employees:

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

departments:

department_id department_name
10 HR
20 IT
30 Marketing
40 Sales

A RIGHT JOIN query would look like this:

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

Result:

name department_name
John HR
Alice IT
Bob Marketing
NULL Sales

Key Points:

  1. All rows from the departments table are returned, even if there's no matching row in employees.
  2. The name column is NULL for the Sales department since there is no corresponding employee in that department.
  3. If a department had no employees, the result would still include the department with NULL in the employee-related columns.

Use Cases:

  • When you want to include all records from the right table and only the matching records from the left table.
  • For example, finding all departments and the employees working in them, even if some departments don't have employees.

No comments:

Post a Comment