SQL LEFT JOIN Keyword
The LEFT JOIN
(also known as 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, regardless of whether there's a match in the right-hand table.
LEFT JOIN: Definition and Usage
A LEFT JOIN
is very useful when you want to retrieve all the 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 result. However, the columns from the right-hand table will contain NULL
values for those unmatched rows.
Syntax
Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name
ORDER BY column_name;
Example
Joining Customers and Orders
This example uses a LEFT JOIN
to retrieve all customers and their associated orders. If a customer has placed orders, the order IDs will be shown. If a customer hasn't placed any orders, the `OrderID` column will be NULL
for that customer. (Assumes 'Customers' and 'Orders' tables exist with a common `CustomerID` column.)
Syntax
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Output
CustomerName | OrderID
---------------------------------
(All customers will be listed; OrderID will be NULL if the customer has no orders.)