21
NovUnderstanding LEFT JOIN in SQL: A Simple Guide
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:
- It begins by retrieving all records from the left table (table1).
- Then, it checks for matching records in the right table (table2) based on the condition provided in the
ON
clause. - The result contains the columns from both tables if there is a match.
- 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_id | employee_name | department_id |
---|---|---|
1 | John | 10 |
2 | Sarah | 20 |
3 | Mike | 30 |
4 | Kate | NULL |
departments table:
department_id | department_name |
---|---|
10 | HR |
20 | Sales |
30 | IT |
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_name | department_name |
---|---|
John | HR |
Sarah | Sales |
Mike | IT |
Kate | NULL |
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
CustomerID | CustomerName |
1 | Rahul |
2 | Priya |
3 | Suresh |
Orders Table
OrderID | CustomerID | OrderDate |
1 | 1 | 2023-02-10 |
2 | 2 | 2022-11-25 |
3 | 1 | 2023-04-05 |
4 | 3 | 2023-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
CustomerName | OrderDate |
Rahul | 2023-02-10 |
Rahul | 2023-04-05 |
Priya | NULL |
Suresh | 2023-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
- 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.