πΈ SQL LEFT JOIN β Include All Left Rows with Examples
π§² Introduction β What is SQL LEFT JOIN?
A LEFT JOIN
returns all records from the left table and the matched records from the right table. If there’s no match, the result from the right side is NULL
.
π― In this guide, youβll learn:
- Syntax and structure of
LEFT JOIN
- Use cases with real examples
- Key differences from INNER JOIN and RIGHT JOIN
β 1. LEFT JOIN Syntax
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.key = table2.key;
β Ensures that every row from the left table appears in the result.
π§Ύ 2. Example β Customers with or without Orders
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id;
β Shows all customers, even those who havenβt placed any orders.
π§© 3. LEFT JOIN vs INNER JOIN
-- INNER JOIN excludes non-matching rows
-- LEFT JOIN includes all rows from the left table
β Use LEFT JOIN when you need to preserve unmatched left rows.
π 4. LEFT JOIN with Filtering (Important!)
-- Correct way to filter on right-side columns:
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
WHERE o.status = 'pending';
β οΈ This behaves like an INNER JOIN because NULLs are excluded. To preserve unmatched left rows:
WHERE o.status = 'pending' OR o.status IS NULL
π 5. LEFT JOIN with Aggregates
SELECT c.id, c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
GROUP BY c.id, c.name;
β Includes customers with zero orders.
π Best Practices
β Recommended | β Avoid This |
---|---|
Use LEFT JOIN to include unmatched data | Filtering right-side columns without handling NULL |
Always test for NULL in the WHERE clause | Assuming LEFT JOIN behaves like INNER JOIN |
Combine with aggregates for summary | Ignoring NULLs in analysis |
π Summary β Recap & Next Steps
The LEFT JOIN
is your go-to when you want to preserve all data from the left table, regardless of whether a match exists on the right.
π Key Takeaways:
- Returns all rows from the left, matching from right
- NULLs fill gaps from unmatched right-side records
- Great for finding missing or optional data
βοΈ Real-World Relevance:
Used in reports, outer lookups, dashboards, and data completeness checks.
β‘οΈ Next: Learn RIGHT JOIN
for mirrored logic, or explore FULL JOIN
for both sides.
β FAQ β SQL LEFT JOIN
β What is the purpose of LEFT JOIN?
β To return all rows from the left table, even if there are no matching rows in the right table.
β What fills unmatched columns from the right table?
β
NULL
values.
β How is LEFT JOIN different from RIGHT JOIN?
β LEFT JOIN keeps left table rows; RIGHT JOIN keeps right table rows.
β Can I use LEFT JOIN with multiple tables?
β Yes. Chain them just like multiple INNER JOINs.
Share Now :