Labs ICT
Pro Login

RIGHT JOIN

RIGHT JOIN is the mirror image of LEFT JOIN. It keeps all rows from the right table and matches from the left. If there is no match on the left, you get NULLs.

Honestly? I rarely use RIGHT JOIN. Most developers just use LEFT JOIN and flip the table order if needed. But you should know it exists.

RIGHT JOIN Example

-- This RIGHT JOIN keeps all courses, even if no one enrolled
SELECT s.name, c.course_name
FROM students s
RIGHT JOIN enrollments e ON s.id = e.student_id
RIGHT JOIN courses c ON e.course_id = c.id;

Notice that all courses show up. If a course has no enrollments (we do not have one in our data, but imagine), it would still appear with NULLs.

LEFT JOIN is More Common

Here is a tip: SQLite does not even support RIGHT JOIN natively. If you try it in our compiler, it will not work. I am teaching it here because other databases like MySQL and PostgreSQL do support it. But in practice, people just write:

-- Instead of RIGHT JOIN, just flip the tables with LEFT JOIN:
SELECT s.name, c.course_name
FROM courses c
LEFT JOIN enrollments e ON c.id = e.course_id
LEFT JOIN students s ON e.student_id = s.id;

Same result, no RIGHT JOIN needed. This is the approach most SQL developers use in the real world.