6.2 — LEFT JOIN in Practice
What You'll Learn
- How to use
LEFT JOIN
to include all rows from one table, even if there's no match in the other - How this compares to Excel's VLOOKUP with missing values
- Practical examples
Sample Tables
Table sales:
ProductID | Amount |
---|---|
101 | 120 |
102 | 80 |
103 | 50 |
Table products:
ProductID | ProductName |
---|---|
101 | Apples |
102 | Oranges |
104 | Bananas |
Why Use LEFT JOIN?
In Excel, if your VLOOKUP doesn’t find a match, you get #N/A
. In SQL, LEFT JOIN
keeps all rows from the left table and fills in NULL
for missing matches.
Example: Show all sales, even if product info is missing
sql
SELECT s.ProductID, p.ProductName, s.Amount
FROM sales s
LEFT JOIN products p
ON s.ProductID = p.ProductID;
- All sales are shown, even if there’s no matching product in
products
. - Missing product names will appear as
NULL
.
Filtering for Missing Matches
You can find rows with no match using WHERE
:
sql
SELECT s.ProductID, s.Amount
FROM sales s
LEFT JOIN products p
ON s.ProductID = p.ProductID
WHERE p.ProductID IS NULL;
- This shows sales with no matching product in the
products
table.
Key Points
LEFT JOIN
keeps all rows from the first (left) table.- Use it to find missing data or keep unmatched rows from the LEFT table.
Next Steps
Next, you’ll learn how to join more than two tables for advanced analysis.