RIGHT JOIN
A RIGHT JOIN
returns all rows from the right table, plus any matching rows from the left table.
If there's no match, 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 comes after
RIGHT JOIN
- All rows from the right table appear in the result, matched or not
Example: Students and Enrollments
Below is an example of a RIGHT JOIN
between the students
and enrollments
tables.
students
student_id | name |
---|---|
1 | John Smith |
2 | Emily Davis |
3 | Michael Brown |
4 | Jessica Lee |
5 | David Johnson |
enrollments
student_id | class_name |
---|---|
1 | Math |
2 | History |
3 | Science |
6 | Art |
7 | Economics |
RIGHT JOIN example
SELECT students.name, enrollments.class_name
FROM students
RIGHT JOIN enrollments
ON students.student_id = enrollments.student_id;
Result:
name | class_name |
---|---|
John Smith | Math |
Emily Davis | History |
Michael Brown | Science |
NULL | Art |
NULL | Economics |
The classes
Art
andEconomics
have no matching students, so thename
isNULL
.
When do I use RIGHT JOIN?
Use RIGHT JOIN
when:
- You need to preserve every row from the right-side table
- You're identifying missing or unmatched data from the left
- The right table is the one you care most about auditing or reporting
Note: SQLite does not support
RIGHT JOIN
natively. You can workarounds like subqueries orLEFT JOIN
with table order reversed.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.