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 fromtable2will appear in the result, withNULLvalues in place of columns fromtable1where there is no match.
Example:
Consider two tables:
-
employees(table1):employee_id name 1 John 2 Alice -
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 JOINensures that all rows from thedepartmentstable appear in the result. - Since there is no employee with
employee_id = 3in theemployeestable, the result showsNULLfor thenamefield for theITdepartment.
No comments:
Post a Comment