Skip to main content
Practice

RIGHT JOIN

A RIGHT JOIN returns all rows from the right table, along with any matching rows from the left table.

If there's no match, the columns from the left table will contain NULL.


Syntax

Here is the syntax for a RIGHT JOIN:

RIGHT JOIN Syntax
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
  • The right table (table2) comes after the RIGHT JOIN keyword
  • All rows from the right table appear in the result, whether or not they have a match

Example: Students and Enrollments

Below is an example of a RIGHT JOIN between the students and enrollments tables.

students

student_idname
1John Smith
2Emily Davis
3Michael Brown
4Jessica Lee
5David Johnson

enrollments

student_idclass_name
1Math
2History
3Science
6Art
7Economics
RIGHT JOIN example
SELECT students.name, enrollments.class_name
FROM students
RIGHT JOIN enrollments
ON students.student_id = enrollments.student_id;

Result:

nameclass_name
John SmithMath
Emily DavisHistory
Michael BrownScience
NULLArt
NULLEconomics

The classes Art and Economics have no matching students, so their name values are NULL.


LEFT JOIN vs RIGHT JOIN

Both joins return unmatched rows, but from opposite sides:

  • LEFT JOIN → keeps all rows from the left table, adds matches from the right
  • RIGHT JOIN → keeps all rows from the right table, adds matches from the left

In essence, they are mirror images of each other.

In practice,LEFT JOIN is used more frequently, and a RIGHT JOIN can usually be rewritten as a LEFT JOIN by swapping the table order.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.