Subqueries and CTEs
Scalar and multi-row subqueries
Compare a value with one-row and multi-row subquery results.
Lesson 39 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. Compare a value with one-row and multi-row subquery results.
Run the example
sql
SELECT ProductID, ProductName, ListPrice
FROM dbo.Products
WHERE ListPrice > (SELECT AVG(ListPrice) FROM dbo.Products)
ORDER BY ProductID;Read it step by step
- The inner AVG returns one scalar price from all 15 products.
- The outer WHERE compares each ListPrice with that single value.
- ORDER BY ProductID makes the matching rows repeatable. IN can compare against a multi-row subquery instead.
Check the result
| ProductID | ProductName | ListPrice |
|---|---|---|
| 2 | USB-C Dock | 129.00 |
| 3 | Webcam | 79.00 |
| 7 | Headphones | 89.00 |
| 9 | Microphone | 119.00 |
| 13 | Desk Chair | 189.00 |
| 14 | Side Table | 95.00 |
| 15 | Shelf Unit | 149.00 |
The average is about 74.37; the result contains products priced above it.
Practice
Return products whose CategoryID is among the categories named Computing or Office.
Check your answer and expected result
Reveal answer
sql
SELECT ProductID, ProductName
FROM dbo.Products
WHERE CategoryID IN (
SELECT CategoryID FROM dbo.Categories
WHERE CategoryName IN (N'Computing', N'Office')
)
ORDER BY ProductID;| ProductID | ProductName |
|---|---|
| 1 | Laptop Stand |
| 2 | USB-C Dock |
| 3 | Webcam |
| 4 | Notebook |
| 5 | Pen Set |
| 6 | Desk Lamp |
The inner query supplies two category IDs; IN keeps products in either category.
Your progress
Reveal the check answer or reach the end to complete this lesson.