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.columnandtable2.column: Specifies the columns used to match rows from both tables.- If a row from
table2has no corresponding match intable1, the result will containNULLfor the columns oftable1.
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:
- All rows from the
departmentstable are returned, even if there's no matching row inemployees. - The
namecolumn isNULLfor theSalesdepartment since there is no corresponding employee in that department. - If a department had no employees, the result would still include the department with
NULLin 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