Joins and set operations
LEFT and RIGHT OUTER JOIN
Preserve one side of a relationship while counting optional matches.
Lesson 34 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Intermediate
On this page4 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Preserve one side of a relationship while counting optional matches.
Run the example
SELECT TOP (5) c.CustomerID, COUNT(o.OrderID) AS OrderCount
FROM dbo.Customers AS c
LEFT JOIN dbo.Orders AS o ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerID
ORDER BY c.CustomerID;Read it step by step
- LEFT JOIN preserves every customer even if no order matches.
- COUNT(o.OrderID) counts matched orders; it would be zero for a customer with none.
- Grouping restores one row per customer, and ORDER BY fixes the TOP (5) sample.
Check the result
| CustomerID | OrderCount |
|---|---|
| 1 | 250 |
| 2 | 250 |
| 3 | 250 |
| 4 | 250 |
| 5 | 250 |
Every customer has orders in the unmodified dataset; the outer join still expresses the intended preserve-customers rule.
Practice
Use RIGHT JOIN to preserve every category while counting inactive products in it.
Check your answer and expected result
Reveal answer
SELECT c.CategoryID, COUNT(p.ProductID) AS InactiveProducts
FROM dbo.Products AS p
RIGHT JOIN dbo.Categories AS c
ON p.CategoryID = c.CategoryID AND p.IsActive = 0
GROUP BY c.CategoryID
ORDER BY c.CategoryID;| CategoryID | InactiveProducts |
|---|---|
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
RIGHT JOIN preserves all five categories. A category with no inactive product still appears with count zero.
Your progress
Reveal the check answer or reach the end to complete this lesson.