MySQL Tutorial
A RIGHT JOIN in MySQL returns all records from the right table (second table) and the matching records from the left table (first table).
SELECT table1.column_name, table2.column_name FROM table1 RIGHT JOIN table2 ON table1.common_column = table2.common_column;
table1
→ Left tabletable2
→ Right tableON
→ Specifies the condition to join the tables using a common column.Consider two tables:
student_id |
name |
gender |
city |
age |
score |
course_id |
|
phone_number |
---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
course_name |
course_name |
---|---|
101 |
Math |
102 |
Science |
103 |
History |
104 |
English |
The following SQL statement will select all courses, and their Enrolled Students:
Try it yourself
name |
course_name |
---|---|
Alice |
Math |
David |
Math |
Charlie |
Science |
Alice |
Science |
Eve |
History |
Frank |
History |
NULL |
English |
NULL
is displayed for the name
.