Wednesday, December 18, 2024

SQL RIGHT JOIN Keyword

 The SQL RIGHT JOIN keyword 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 (the table mentioned after RIGHT JOIN) are included in the result, even if there is no match in the left table. If there is no match, the result will include NULL values for columns from the left table.

Syntax:

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

Explanation:

  • table1: The left table in the join.
  • table2: The right table in the join.
  • common_column: The column used to match rows between the two tables.
  • RIGHT JOIN: Ensures that all rows from table2 will appear in the result, with NULL values in place of columns from table1 where there is no match.

Example:

Consider two tables:

  1. employees (table1):

    employee_id name
    1 John
    2 Alice
  2. departments (table2):

    department_id employee_id department_name
    1 1 HR
    2 3 IT

SQL query using RIGHT JOIN:

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

Result:

name department_name
John HR
NULL IT

Explanation:

  • The RIGHT JOIN ensures that all rows from the departments table appear in the result.
  • Since there is no employee with employee_id = 3 in the employees table, the result shows NULL for the name field for the IT department.

No comments:

Post a Comment