
Right Join in MySql
RIGHT JOIN in MySQL
The RIGHT JOIN
(or RIGHT OUTER JOIN
) in MySQL returns all records from the right table and the matching records from the left table. If no match is found, NULL values are returned for the left table.
1. Syntax
SELECT columnsFROM left_tableRIGHT JOIN right_tableON left_table.common_column = right_table.common_column;
- left_table β The table on the left side of the
JOIN
clause. - right_table β The table on the right side of the
JOIN
clause. - If thereβs no match, NULL values appear in the left tableβs columns.
2. Example Tables
π Table: departments
(Right Table)
dept_id | dept_name |
---|---|
1 | IT |
2 | HR |
3 | Finance |
π Table: employees
(Left Table)
emp_id | name | dept_id |
---|---|---|
101 | Alice | 1 |
102 | Bob | 2 |
103 | Charlie | NULL |
3. RIGHT JOIN Example
SELECT employees.emp_id, employees.name, departments.dept_nameFROM employeesRIGHT JOIN departments ON employees.dept_id = departments.dept_id;
β Result:
emp_id | name | dept_name |
---|---|---|
101 | Alice | IT |
102 | Bob | HR |
NULL | NULL | Finance |
Explanation:
- Alice and Bob have matching department IDs.
Finance
department has no matching employee, soNULL
appears inemp_id
andname
.
4. Difference Between RIGHT JOIN and LEFT JOIN
Feature | LEFT JOIN | RIGHT JOIN |
---|---|---|
Returns all rows from | Left Table | Right Table |
Unmatched rows appear as | NULL in Right Table | NULL in Left Table |
π‘ Example of LEFT JOIN (Opposite of RIGHT JOIN):
SELECT employees.emp_id, employees.name, departments.dept_nameFROM employeesLEFT JOIN departments ON employees.dept_id = departments.dept_id;
5. RIGHT JOIN with WHERE Clause
To filter results:
SELECT employees.emp_id, employees.name, departments.dept_nameFROM employeesRIGHT JOIN departments ON employees.dept_id = departments.dept_idWHERE departments.dept_name = 'Finance';
β Result:
emp_id | name | dept_name |
---|---|---|
NULL | NULL | Finance |
Key Takeaways
β
RIGHT JOIN
returns all rows from the right table and matches from the left table.
β
If no match is found, NULL values appear in the left table columns.
β
Use WHERE
to filter results.
β
Opposite of LEFT JOIN
.