T-SQL Tutorial

T-SQL LEFT JOIN


In SQL Server, a LEFT JOIN is a type of join that returns all the records from the left table and only the matching records from the right table. This means that even if there are no matches in the right table, the left table records will still be returned.

To perform a LEFT JOIN in SQL Server, you use the JOIN keyword followed by the LEFT OUTER JOIN keyword, and then specify the tables you want to join and the columns you want to retrieve.


Syntax

The basic syntax for a LEFT JOIN in SQL Server is as follows:

SELECT column1, column2, ...
FROM table1
LEFT OUTER JOIN table2
ON table1.column = table2.column;

In this syntax, the SELECT statement specifies the columns you want to retrieve from the tables, while the FROM clause specifies the left table, which is table1 in this case. The LEFT OUTER JOIN keyword specifies the type of join to use, and the ON clause specifies the join condition, which is the column to join on.


Example

For example, let's say you have two tables, orders and customers, with the following data:


Orders table

order_idcustomer_idorder_date
11012022-01-01
21022022-01-02
31032022-01-03
41012022-01-04

Customers able

CUSTOMER_IDCUSTOMER_NAME
101John Smith
102Jane Doe

To retrieve all the orders and the corresponding customer names (if available), you can use a LEFT JOIN like this:

SELECT orders.order_id, customers.customer_name
FROM orders
LEFT OUTER JOIN customers
ON orders.customer_id = customers.customer_id;


Result:

This query will return the following result:

order_idcustomer_name
1John Smith
2Jane Doe
3NULL
4John Smith

As you can see, the LEFT JOIN returns all the orders from the orders table, and the matching customer names from the customers table. However, since there is no customer with customer_id 103 in the customers table, the corresponding customer_name column is NULL in the result set.

Overall, the LEFT JOIN in SQL Server is a useful tool for combining data from multiple tables, and it ensures that all the records from the left table are included in the result set, even if there are no matches in the right table.