Microsoft SQL Server

Chapter 7 - DQL (Data Query Language)

LEFT JOIN

In Microsoft SQL Server, the LEFT JOIN clause is used to retrieve all rows from the left (first) table and matching rows from the right (second) table. If there is no match in the right table, the result will contain NULL for the columns of the right table. This is especially useful when you need to retrieve all records from one table even if there are no corresponding records in the other. For beginners, understanding how to use LEFT JOIN helps in querying data where some records may not have corresponding matches but still need to be included in the results.

Below is a detailed explanation of how to use the LEFT JOIN clause with examples and best practices.

1. Basic Syntax of LEFT JOIN

The basic syntax of LEFT JOIN is as follows:

SELECT table1.column1, table2.column2 FROM table1 LEFT JOIN table2 ON table1.common_column = table2.common_column;
  • table1 is the left table, which will return all its rows.
  • table2 is the right table, from which matching rows will be returned, or NULL if no match exists.

Example:

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

This query retrieves all customers, including those who have not placed any orders. If a customer has no order, NULL will appear in the OrderDate column.

2. Handling NULL Values in LEFT JOIN

When there is no match in the right table, LEFT JOIN returns NULL values for the columns of the right table.

SELECT Products.ProductName, Sales.SaleDate FROM Products LEFT JOIN Sales ON Products.ProductID = Sales.ProductID;

This query retrieves all products, including those that have never been sold, with NULL in the SaleDate column for unsold products.

3. Using LEFT JOIN with Multiple Tables

You can join more than two tables using multiple LEFT JOIN clauses.

SELECT Customers.CustomerName, Orders.OrderDate, Products.ProductName FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID LEFT JOIN Products ON Orders.ProductID = Products.ProductID;

This query retrieves all customers and their orders, along with the corresponding products. Even if a customer hasn’t placed an order, they will still be included in the result set, with NULL values for order and product information.

4. Filtering Results in LEFT JOIN

To filter rows from the left table based on the results of the LEFT JOIN, use a WHERE clause.

SELECT Customers.CustomerName, Orders.OrderDate FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Orders.OrderDate IS NULL;

This query retrieves all customers who have not placed any orders by filtering for rows where OrderDate is NULL.

5. Using LEFT JOIN with Aggregates

LEFT JOIN can also be used with aggregate functions to calculate values, such as counting the number of related rows in the right table.

SELECT Customers.CustomerName, COUNT(Orders.OrderID) AS TotalOrders FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CustomerName;

This query returns each customer's name along with the number of orders they have placed. Customers who have not placed any orders will show a count of 0.

6. Best Practices for Using LEFT JOIN

  1. Use LEFT JOIN When You Need All Rows from the Left Table – The LEFT JOIN is ideal when you need to retrieve all records from the left table, regardless of whether matching rows exist in the right table.

    SELECT Customers.CustomerName, Orders.OrderDate FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
  2. Be Aware of NULL ValuesLEFT JOIN often introduces NULL values in the result set for columns from the right table. Ensure your queries handle NULL values properly, especially in conditions or calculations.

    SELECT ProductName, SaleDate FROM Products LEFT JOIN Sales ON Products.ProductID = Sales.ProductID WHERE Sales.SaleDate IS NULL;
  3. Combine with WHERE for Filtering Results – Use the WHERE clause to filter results, including or excluding rows based on the presence of NULL values in the right table.

    SELECT * FROM Products LEFT JOIN Sales ON Products.ProductID = Sales.ProductID WHERE Sales.SaleDate IS NULL;
  4. Index Join Columns for Performance – To improve performance, ensure that the columns used to join tables (e.g., CustomerID, ProductID) are indexed, especially when joining large tables.

  5. Test Queries with Different Data Scenarios – When working with LEFT JOIN, test your queries with scenarios where matching records exist and where they do not, to ensure the query returns the correct results.

By mastering the LEFT JOIN clause, you can efficiently retrieve data from related tables, ensuring that all relevant rows from the left table are included, even when there are no corresponding records in the right table. This is useful for generating comprehensive reports and analyzing data with missing relationships.

Tansy SQL Course | LEFT JOIN | Chapter 7 | Lesson 25 - Video Thumbnail

Test code

In Microsoft SQL Server, to retrieve product information along with the corresponding orders using a LEFT JOIN to include products that have not been ordered, you can use the following query:

SELECT prd_product.product_id, 
prd_product.product_code, 
prd_product.product_name,
act_order_detail.order_id
FROM prd_product
LEFT JOIN act_order_detail ON act_order_detail.product_id = prd_product.product_id
ORDER BY prd_product.product_id, act_order_detail.order_id;
Try it now

To choose orders that have not received any payments yet using a LEFT JOIN from the orders table into the payments table, where orders without any corresponding payment will be represented on the payments side as NULL, and apply a filter with IS NULL on the payment side to compile a list of orders lacking any payment, you can use the following query:

SELECT a.order_number,
a.order_date,
b.payment_id
FROM act_order a
LEFT JOIN act_payment b ON b.order_id = a.order_id
ORDER BY a.order_number;

-- To filter orders that have not received any payments yet
SELECT a.order_number,
a.order_date
FROM act_order a
LEFT JOIN act_payment b ON b.order_id = a.order_id
WHERE b.order_id IS NULL;
Try it now

To present a thorough list of customers, including those without any orders, and showcase the total value of orders accumulated throughout their entire lifetime, you can use the following query:

SELECT org_client.client_id, 
org_client.first_name AS client_name,
SUM(act_order.sub_total) AS lifetime_order_amount
FROM org_client
LEFT JOIN act_order ON act_order.client_id = org_client.client_id
GROUP BY org_client.client_id, org_client.first_name
ORDER BY org_client.client_id;
Try it now

EXAMPLE 1 - SQL LEFT JOIN

Here is a clear example of a LEFT JOIN. Retrieve information of all products along with their respective order details, including products that have not been associated with any orders.

EXAMPLE 1 - Tansy Academy Data Model

i

In this task, you will create a query involving two tables, named Products and Order details, marked are the columns necessary for the query.

EXAMPLE 1 - LEFT JOIN query

To achieve this, you need to execute a LEFT JOIN between the product table and the order detail table, utilizing the primary key and foreign key column, wherein the product ID column serves as the joining column. In this scenario, the product table functions as the left table, and the order detail table is considered the right table. The left table, which contains the essential primary business information, focuses on the product list as the primary requirement. At a secondary level, we seek order IDs, so we treat the order details as the secondary table, positioned on the right side of the join

SELECT prd_product.product_id, prd_product.product_code, prd_product.product_name ,act_order_detail.order_id FROM prd_product LEFT JOIN act_order_detail ON act_order_detail.product_id = prd_product.product_id ORDER BY prd_product.product_id, act_order_detail.order_id;

EXAMPLE 1 - Query Data Mapping

i

In this visual representation, a yellow background denotes a correspondence between the primary key and foreign key. Meanwhile, a light yellow background with red font on the left side signifies products lacking a corresponding row in the order details table. These products will be included in the final result, but with NULL values for order IDs. It's important to recognize that a LEFT JOIN incorporates all rows from the left table, which, in this case, is the product table.

EXAMPLE 1 - Final OUTput

i

In this view, it's evident that certain product records from the left table have multiple corresponding rows on the right side. Consequently, the product information will be associated with each order entry from the right side.

Comments(0 comments)

Comments Not Found