Sql Right Join

Sql Right Join

Blog Bustle 09/04/2020

Sql right join is used to fetch all data of right table(table 2) and that left table(table 1) data where at least one column value is matched with right table column value and these columns define relationship between both tables and after defining relationship if value does not match, left table data for that right column value would be null.

Sql right join syntax

SELECT table_1.*,table_2.* FROM table_1
RIGHT JOIN table_2
ON table_1.common_column = table_2.common_column;

Sql right join examples

Let's look at some examples to understand sql right join.

I have two tables named student and student_fees.

id name email
1 justin justin@gmail.com
2 michael michael@gmail.com
3 kevin kevin@gmail.com
4 robert robert@gmail.com
id student_id class_name admission_fee
1 1 6 600
2 2 7 700
3 3 6 600
4 5 8 800

Find student's name,email and class. Use student table as table 1 and student_fees as table 2 and sql query will be

SELECT name,email,class_name
FROM student
RIGHT JOIN student_fees
ON student.id = student_fees.student_id;

We can also write this query using sql alias.

SELECT s.name,s.email,sf.class_name
FROM student as s
RIGHT JOIN student_fees as sf
ON s.id = sf.student_id;

After running this sql query, result will be

name email class_name
justin justin@gmail.com 6
michael michael@gmail.com 7
kevin kevin@gmail.com 6
NULL NULL 8

Find class and email of students whose admission fee is greater than $600 and sql query will be

SELECT s.email,sf.class_name
FROM student as s
RIGHT JOIN student_fees as sf
ON s.id = sf.student_id
WHERE sf.admission_fee > 600;

After running this sql query, result will be

email class_name
michael@gmail.com NULL
7 8

After looking at these examples, we can easily understand and use sql right join. Hope you like this tutorial.

Other important links

Sql Left Join

Sql Inner Join

Sql Aliases

Sql Group By clause

Sql Limit clause

Sql Right Join searches:

Tags: #mysql