SQL LEFT JOIN Keyword

The LEFT JOIN (sometimes called a LEFT OUTER JOIN) keyword in SQL combines rows from two tables based on a related column. Unlike an INNER JOIN, which only returns rows with matches in both tables, a LEFT JOIN returns all rows from the left-hand table, even if there isn't a match in the right-hand table.



LEFT JOIN: Definition and Usage

A LEFT JOIN is very useful when you want to retrieve all data from the left-hand table and any corresponding data from the right-hand table. If a row in the left-hand table doesn't have a match in the right-hand table (based on your join condition), that row is still included in the results. However, the columns from the right-hand table will contain NULL values for those unmatched rows. This helps you see which rows in the left table have related data in the right table and which don't.

Syntax

Syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
      

Example Databases

The example below uses simplified versions of the 'Customers' and 'Orders' tables:

Customers Table (Sample Data)

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

Orders Table (Sample Data)

OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2

Example: LEFT JOIN

This query shows all customers and their orders. Customers without orders will have a NULL value in the `OrderID` column.

Syntax

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
      
Output

CustomerName             | OrderID
---------------------------------
Alfreds Futterkiste      | NULL
Ana Trujillo Emparedados y helados | 10308
Antonio Moreno Taquería | NULL
(Further rows would be displayed here based on the data in your tables.)
      

**Note:** The example output is partial; a complete result would include all rows from the `Customers` table. The `NULL` values indicate that those customers do not have any associated orders in the `Orders` table. The specific `OrderID` values will depend on the data in your `Orders` table. The rows are sorted alphabetically by `CustomerName` due to the `ORDER BY` clause.