Joining Tables in SQL

Right Join

Learn how to combine data from multiple tables using SQL Joins.

Course Sections
Objectives
    • Understand what a Right Join is.
    • Learn how to use Right Joins to combine data from multiple tables.
    • Practice using Right Joins.

What is a Right Join?

A Right Join is used to return all rows from the right table and the matched rows from the left table.

Syntax

 SELECT *
FROM left_table
RIGHT JOIN right_table
ON left_table.column_name = right_table.column_name; 

Example

Consider the following tables:

left_table
idname
1Alice
2Bob
right_table
idage
125
227

When we use a right join, we will get all the rows from the right table and the matched rows from the left table.

 SELECT *
FROM left_table
RIGHT JOIN right_table
ON left_table.id = right_table.id; 
output
idnameage
1Alice25
2Bob27

In the above example, the left table has two rows, and the right table has two rows.

What would happen if there was missing data in the left table?

Tables with missing data

Consider the following example. We don’t have a name for the person with id 2 in the left table.

left_table
idname
1Alice
right_table
idage
125
227

We use the same right join query as before.

 SELECT *
FROM left_table
RIGHT JOIN right_table
ON left_table.id = right_table.id; 

If there is no match in the left table, the columns from the left table will be NULL .

output
idnameage
1Alice25
2NULL27

Exercise 3.1

There are two tables fruits and prices . Fill in the blanks to complete the SQL statement to join the fruits and prices tables on the id column using a Right Join.
fruits
idname
1Apple
2Banana
3Orange
prices
idprice
110
25
Interactive
Right Join
  •  SELECT fruits.id, fruits.name, prices.price
    FROM fruits
    RIGHT JOIN prices
    ON fruits.id = prices.id; 

Exercise 3.2

There are two tables students and grades . Fill in the blanks to complete the SQL statement to join the students and grades tables on the student_id column using a Right Join.
students
student_idname
1Alia
2Babu
3Coco
grades
student_idgrade
1O
2A+
Interactive
Right Join
  •  SELECT students.student_id, students.name, grades.grade
    FROM students
    RIGHT JOIN grades
    ON students.student_id = grades.student_id; 

Summary

In this section, we learned about Right Joins and how to use them to combine data from multiple tables.