SQL LEFT JOIN

The SQL LEFT JOIN clause is used to retrieve all rows from the left table (the first table in the JOIN), and the matching rows from the right table. If there is no match, the result is NULL on the side of the right table.

This join is useful when you want to retain all records from the left table, even if there are no corresponding records in the right table.

Tables Used

Orders Table:
OrderID Product CustomerID
1 Laptop 101
2 Phone 102
3 Tablet NULL
Customers Table:
CustomerID CustomerName
101 Alice
102 Bob
103 Charlie

Example

We’ll perform a LEFT JOIN to include all rows from the Orders table, even if there is no match in the Customers table.

Code Example


-- Perform a LEFT JOIN between Orders and Customers
SELECT Orders.OrderID, Orders.Product, Customers.CustomerName
FROM Orders
LEFT JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;

-- View the resulting table
            

Output Table

OrderID Product CustomerName
1 Laptop Alice
2 Phone Bob
3 Tablet NULL

Explanation

- The LEFT JOIN ensures all rows from the Orders table are included.
- For rows without a match in the Customers table, the CustomerName is NULL.