In SQL, a `RIGHT JOIN` is a type of join operation used to combine rows from two tables based on the right table's values. It returns all the rows from the right table and the matching rows from the left table. If there is no match, NULL values are returned for the columns from the left table.
The basic syntax for a `RIGHT JOIN` is as follows:
sql
SELECT column_list
FROM table1
RIGHT JOIN table2 ON join_condition;
Here's a breakdown of the components:
- `column_list`: The list of columns you want to select from the resulting joined table.
- `table1`: The left table in the join operation.
- `table2`: The right table in the join operation.
- `join_condition`: The condition that determines how the two tables are related.
To illustrate this further, let's consider two tables: `employees` and `departments`, with the following structures:
employees
-----------------------------
| emp_id | emp_name | dept_id |
-----------------------------
| 1 | John | 101 |
| 2 | Jane | 102 |
| 3 | Alice | 103 |
| 4 | Bob | 104 |
-----------------------------
departments
---------------------
| dept_id | dept_name |
---------------------
| 101 | Sales |
| 103 | Finance |
| 105 | IT |
---------------------
Suppose you want to retrieve all employees and their corresponding department names, including those employees who don't have a department assigned (i.e., employees without a matching department record). You can use a `RIGHT JOIN` as follows:
sql
SELECT employees.emp_id, employees.emp_name, departments.dept_name
FROM employees
RIGHT JOIN departments ON employees.dept_id = departments.dept_id;
---------------------------------------------------
| emp_id | emp_name | dept_name |
---------------------------------------------------
| 1 | John | Sales |
| 2 | Jane | NULL (No matching department)|
| 3 | Alice | Finance |
| 4 | Bob | NULL (No matching department)|
---------------------------------------------------
In this example, the `RIGHT JOIN` returns all rows from the `departments` table and the matching rows from the `employees` table. If an employee doesn't have a matching department record, NULL values are displayed for the department columns.
Keep in mind that the usage of `RIGHT JOIN` may vary depending on the specific database system you are using.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc