SQL Tutorial
The LEFT JOIN
keyword in SQL is used to return all records from the left table (Table1), and the matched records from the right table (Table2). If there is no match, the result is NULL on the right side.
Here's the basic syntax for a LEFT JOIN
:
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
Example:
Consider the following two tables:
Orders
table:
OrderID | CustomerID | OrderAmount |
---|---|---|
1 | 3 | 100 |
2 | 1 | 160 |
3 | 2 | 70 |
4 | 5 | 240 |
Customers
table:
CustomerID | Name |
---|---|
1 | John |
2 | Jane |
3 | Alice |
4 | Bob |
We can use LEFT JOIN
to combine these tables based on the CustomerID
:
SELECT Customers.Name, Orders.OrderID, Orders.OrderAmount FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
The result would be:
Name | OrderID | OrderAmount |
---|---|---|
John | 2 | 160 |
Jane | 3 | 70 |
Alice | 1 | 100 |
Bob | NULL | NULL |
In this result set, you can see that for customer 'Bob' there are no matching orders, so the OrderID
and OrderAmount
fields for Bob are NULL.
Note:
The LEFT JOIN
keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL on the right side when there is no match.
As always, the exact syntax may vary between different SQL dialects, so be sure to consult the documentation for the SQL dialect you're using.
SQL LEFT JOIN Example:
SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
LEFT JOIN vs INNER JOIN in SQL:
-- INNER JOIN example SELECT * FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name; -- LEFT JOIN example SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
Using WHERE Clause with LEFT JOIN:
SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name WHERE table2.column_name IS NULL;
Handling NULL Values in LEFT JOIN:
SELECT table1.column1, COALESCE(table2.column2, 'N/A') AS column2 FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
Multiple Conditions in LEFT JOIN Statement:
SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 AND table1.column2 = table2.column2;
LEFT JOIN with Multiple Tables in SQL:
SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name LEFT JOIN table3 ON table1.column_name = table3.column_name;