SQL LEFT JOIN

SQL LEFT JOIN is a type of join operation used to combine data from two or more tables based on the values of the columns they have in common. Unlike INNER JOIN, LEFT JOIN returns all the rows from the left table (the first table in the query), and only the matching rows from the right table. If there are no matching rows in the right table, the result will still contain all the rows from the left table, with NULL values in the columns from the right table.

Let's consider two tables, 'Customers' and 'Orders' for the purpose of this example:

Customers Table:

CustomerIDCustomerNameContactNameCountry
1AlfredsMariaGermany
2Ana TrujilloAnaMexico
3AntonioAntonioSpain

Orders Table:

OrderIDCustomerIDOrderDate
132022-12-01
212022-12-02

To join these two tables using LEFT JOIN, we would write the following SQL query:

1SELECT Customers.CustomerName, Orders.OrderDate 2FROM Customers 3LEFT JOIN Orders 4ON Customers.CustomerID = Orders.CustomerID;

This query will return the following result:

CustomerNameOrderDate
Alfreds2022-12-02
Ana TrujilloNULL
Antonio2022-12-01

The query combines the rows from the two tables where the value of the CustomerID column in the 'Customers' table matches the value of the CustomerID column in the 'Orders' table. However, it returns all the rows from the 'Customers' table, regardless of whether there are matching rows in the 'Orders' table. For the 'Ana Trujillo' customer, there is no matching order in the 'Orders' table, so the result for the OrderDate column is NULL.