Logo

K-Learn

SQL RIGHT JOIN

< Previous Next >

SQL Right Join is used to combine two or more tables based on matching values in a specified column(s). In a right join, all the records from the right table are returned, along with matching records from the left table. If there are no matching records in the left table, then the result will contain NULL values for those columns.

RIGHT JOIN Syntax

SELECT column1, column2, …
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;

For example,

SELECT student.name, subject.name, exam.marks
FROM exam
RIGHT JOIN student ON exam.student_id = student.id
RIGHT JOIN subject ON exam.subject_id = subject.id;

OUTPUT

In this above example,

Let's say we want to retrieve a list of all students and their corresponding exam marks for each subject, even if they didn't take any exams.

We can use a right join to achieve this by selecting all columns from the exam table and joining it with the student and subject tables on their respective IDs.

This query will return a list of all students and their corresponding exam marks for each subject, even if they didn't take any exams. If a student didn't take an exam for a particular subject, the marks column will contain a NULL value.


< Previous Next >