Understanding LEFT JOIN in SQL: A Simple Guide

Understanding LEFT JOIN in SQL: A Simple Guide

19 Oct 2024
Beginner
112 Views
13 min read
Learn with an interactive course and practical hands-on labs

SQL Server Course

LEFT JOIN in SQL

Left Join in SQL helps you merge the records from the two tables and keep all the records on the left side of the table. Each row is taken from the left table and compared to the right table; if no matches are discovered, NULLs are entered. This process ensures that no records will be lost.

In the SQL Tutorial, we will explain to you the complete description about what is the Left JOIN in SQL, the syntax of Left Join, how does Left Join work in SQL, key use-cases of LEFT JOIN, the difference between Left Join and INNER Join, Left Join with WHERE Clause,  and many more.

OUTER JOIN in SQL

Outer Joins in SQL combine data from two tables, including all records from one or both tables, regardless of whether there are matching rows.

There are three types of JOINS that are :

  • LEFT OUTER JOIN
  • Right OUTER JOIN
  • Full OUTER JOIN

What is a LEFT JOIN in SQL?

Left Join in SQL is a method that uses a common column to connect data from two tables. It displays every entry from the first table and searches the second table for entries that match. If there are no matches, it still shows everything from the first table, leaving empty spaces for missing data from the second table.

Syntax of LEFT JOIN in SQL

The basic syntax of a LEFT JOIN looks like this:

SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;

Explanation

  • table1: It is the left table (the primary table from which all rows will be returned).
  • table2: It is the right table (the table from which matching records are returned).
  • ON: The condition that specifies how the two tables are joined, usually based on matching columns.

How does JOIN work in SQL?

To understand how Left Join Works in SQL, we have explained some points that are:

  1. It begins by retrieving all records from the left table (table1).
  2. Then, it checks for matching records in the right table (table2) based on the condition provided in the ON clause.
  3. The result contains the columns from both tables if there is a match.
  4. The outcome will still contain every row from the left table with NULL values for the columns from the right table if no match is found..

Example of LEFT JOIN

In this example, we have two tables that are employeesand departments that are given below:

employees table:

employee_idemployee_namedepartment_id
1John10
2Sarah20
3Mike30
4KateNULL

departments table:

department_iddepartment_name
10HR
20Sales
30IT

By the above tables, we want to retrieve all the employees and the department names. So, we use the following SQL commands

SELECT employees.employee_name, departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;

Result:

employee_namedepartment_name
JohnHR
SarahSales
MikeIT
KateNULL

Key Use Cases of LEFT JOIN in SQL

Here are the key use cases that we have discussed below that are:

1. Retrieving Unmatched Data

The LEFT JOINis particularly useful when you want to retrieve all records from one table, even if there are no matching records in the related table. For example, finding employees who do not belong to any department.

SELECT employees.employee_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id
WHERE departments.department_id IS NULL;

This query will return employees with no department assigned.

2. Maintaining Data Completeness

In reporting or analytics, LEFT JOIN ensures that no records are dropped from the left table, which is useful when working with incomplete data or during data migrations.

3. Combining data from multiple sources

When performing operations where some tables might not always contain related data (e.g., combining a list of customers with their orders, where some customers have no orders yet), LEFT JOIN ensures no customer is omitted.

Difference Between LEFT JOIN and INNER JOIN

Here we understand the difference between 'LEFT JOIN' and 'INNER JOIN':

INNER JOIN:It returns only the rows that have matching records in both tables. If there’s no match, the rows are not returned.

SELECT employees.employee_name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;

In this case, the result would exclude any employees without a department (like Kate).

LEFT JOIN:As previously said, LEFT JOIN in SQL returns every entry from the left table, regardless of whether the right table has a match or not.

Left Join with WHERE Clause

A WHERE clause can help you further reduce your results when utilizing a Left Join in SQL. This allows you to filter the results based on specific parameters.The WHERE clause limits the rows according to the criteria you provide, but the Left Join will still contain all data from the left table.

Example

Orders and Customers are your two tables. Only orders placed in 2023 are the ones you wish to retrieve, together with all of the customers and their orders.

Customer Table

CustomerIDCustomerName
1Rahul
2Priya
3Suresh

Orders Table

OrderIDCustomerIDOrderDate
112023-02-10
222022-11-25
312023-04-05
432023-07-15

SQL Query with Left Join and WHERE Clause

SELECT 
    Customers.CustomerName,
    Orders.OrderDate
FROM 
    Customers
LEFT JOIN 
    Orders ON Customers.CustomerID = Orders.CustomerID
WHERE 
    Orders.OrderDate >= '2023-01-01' OR Orders.OrderDate IS NULL;

Explanation

  • Only orders placed in 2023 are included in this query's retrieval of all customers from the Customers dataset and their order dates from the Orders table.
  • The result is narrowed down by the WHERE clause to only show orders placed in 2023 or NULL values for clients who haven't placed any orders.
  • This ensures that you get all customers, such as Rahul, Priya, and Suresh, even if some (like Priya) haven’t placed orders in 2023.

SQL LEFT JOIN as Aliases Example

With the use of SQL aliases, you may give tables or columns temporary names that make writing and reading queries simpler. If you deal with numerous tables, your SQL code can be cleaner by combining aliases with an LEFT JOIN.

Example

Here, we use the Orders and Customer table. Let's understand with the query:

SELECT 
    C.CustomerName,
    O.OrderDate
FROM 
    Customers AS C
LEFT JOIN 
    Orders AS O ON C.CustomerID = O.CustomerID;

Explanation

  • The alias O has been allocated to the Orders table, and the alias C to the Customers table.
  • After the data is combined using an LEFT JOIN, all rows from the Customers table (C) and any matching orders from the Orders table (O) are returned.
  • The order date comes from O, while the client name comes from C in this query. The OrderDate will appear as NULL if a client has no orders.

Result

CustomerNameOrderDate
Rahul2023-02-10
Rahul2023-04-05
PriyaNULL
Suresh2023-07-15

Performance Considerations of LEFT JOIN in SQL

While LEFT JOINs are very useful, be mindful of performance when working with large datasets. JOIN operations can become expensive in terms of computation if you are joining large tables or using complex conditions.

  • Indexes: Ensure that the columns used in the ON condition are indexed. This helps the database engine quickly locate matching rows.
  • Database design: Proper normalization and structuring of your tables can also optimize join performance.
Read More: Top 50 SQL Server Interview Questions and Answers

Conclusion

To sum up, a Left Join in SQL is a method for merging data while ensuring that all of the information from the left table is retained. We have discussed LEFT OUTER JOIN, Syntax, LEFT JOIN examples, and many more. It lets you get matching data from the right table, and in the event that no match is found, it retains all the information from the left table. To master database management with our SQL Server Certification, take the next step in your career by enrolling in the ScholarHat SQL Server Course.

FAQs

If there’s no match in the right table, a Left Join will return the data from the left table, with NULL values for the columns from the right table. 

Yes, you can use a Left Join with multiple tables by chaining multiple joins together. For example, you can join three or more tables by using additional LEFT JOIN statements. 

A Left Join can sometimes be slower than an Inner Join because it returns all rows from the left table and includes unmatched rows from the right table with NULLs. Query performance depends on the size of the tables and indexing. 

Yes, a Left Join can result in duplicate rows if there are multiple matching rows in the right table for a row in the left table. Each match will create a new row in the result set. 

Alternatives to Left Join include:
  • Inner Join: Returns only matching rows.
  • Right Join: Returns all rows from the right table and matches rows from the left.
  • Full Outer Join: Returns all rows when there’s a match in either table, with NULLs for non-matching rows.

Take our Sqlserver skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingNov 08MON, TUE, WED, THU, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Developer Certification TrainingNov 09SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification TrainingNov 17SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingNov 17SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Angular Certification TrainingNov 17SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Software Architecture and Design TrainingNov 24SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 24SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Angular Certification TrainingDec 08SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingDec 14SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingDec 15SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
.NET Microservices Certification TrainingDec 15SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this