Joining Tables in SQL

Left Join

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

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

What is a Left Join?

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

Syntax

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

Example

Think of two tables, the left table and the right table.

Tables with matching data

left_table
idname
1Alice
2Bob
right_table
idage
125
227

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

 SELECT *
FROM left_table
LEFT JOIN right_table
ON left_table.id = right_table.id; 
output (matching data)
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 right table?

Tables with missing data

Consider the following example. We don’t have an age for the person with id 2 in the right table.

left table
idname
1Alice
2Bob
right table
idage
125

We use the same left join query as before.

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

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

output (missing data)
idnameage
1Alice25
2BobNULL

Exercise 2.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 Left Join.
fruits
idname
1Apple
2Banana
3Orange
prices
idprice
110
25
Interactive
Left Join
  •  SELECT *
    FROM fruits
    LEFT JOIN prices
    ON fruits.id = prices.id; 

Exercise 2.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 Left Join.
students
student_idname
1Alia
2Babu
3Coco
grades
student_idgrade
1O
2A+
Interactive
Left Join
  •  SELECT students.student_id, students.name, grades.grade
    FROM students
    LEFT JOIN grades
    ON students.student_id = grades.student_id; 

Summary

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