Subqueries and CTEs
Correlated subqueries
Calculate a related value separately for each outer row.
Lesson 41 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Calculate a related value separately for each outer row.
Run the example
sql
SELECT TOP (5) p.ProductID,
(SELECT COUNT(*) FROM dbo.OrderItems AS i
WHERE i.ProductID = p.ProductID) AS LineCount
FROM dbo.Products AS p
ORDER BY p.ProductID;Read it step by step
- The inner WHERE refers to the current outer ProductID.
- COUNT(*) returns one count for that product, including zero when no line matches.
- TOP (5) with ORDER BY selects five repeatable products.
Check the result
| ProductID | LineCount |
|---|---|
| 1 | 667 |
| 2 | 667 |
| 3 | 667 |
| 4 | 667 |
| 5 | 667 |
The correlation changes the inner count for each product.
Practice
Count orders for Customers 1–3 using a correlated subquery.
Check your answer and expected result
Reveal answer
sql
SELECT c.CustomerID,
(SELECT COUNT(*) FROM dbo.Orders AS o
WHERE o.CustomerID = c.CustomerID) AS OrderCount
FROM dbo.Customers AS c
WHERE c.CustomerID BETWEEN 1 AND 3
ORDER BY c.CustomerID;| CustomerID | OrderCount |
|---|---|
| 1 | 250 |
| 2 | 250 |
| 3 | 250 |
Each customer receives a count of their own orders.
Your progress
Reveal the check answer or reach the end to complete this lesson.