MySQL RIGHT JOIN
MySQL RIGHT JOIN
The RIGHT JOIN (or RIGHT OUTER JOIN) returns all rows from the right table and the matching rows from the left table.
If there is no match, the left table columns will show NULL.
Syntax
-
table1→ Left table -
table2→ Right table -
ON→ Join condition
🧠 Example Tables
Students Table (students)
| student_id | name | dept_id |
|---|---|---|
| 1 | John | 1 |
| 2 | Emma | 2 |
| 3 | Raj | 1 |
| 4 | Sara | 3 |
Departments Table (departments)
| dept_id | dept_name |
|---|---|
| 1 | IT |
| 2 | HR |
| 3 | Finance |
| 4 | Sales |
SQL Query
Result
| name | dept_name |
|---|---|
| John | IT |
| Raj | IT |
| Emma | HR |
| Sara | Finance |
| NULL | Sales |
✅ Notice: Department Sales has no student →
nameshows NULL, but the row is included because it’s in the right table.
Venn Diagram Representation
-
✅ Overlapping area → Matching dept_id rows
-
✅ Right table exclusive → Rows included with NULL for left table
Key Points
-
Returns all rows from the right table.
-
Returns matching rows from the left table, or NULL if no match.
-
Useful when you want to ensure all data from the secondary table is included.
-
Often used to find items that don’t have a corresponding entry in the left table.
