Subqueries and CTEs
EXISTS and NOT EXISTS
Test whether related rows exist without duplicating the outer result.
Lesson 40 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. Test whether related rows exist without duplicating the outer result.
Run the example
sql
SELECT p.ProductID, p.ProductName
FROM dbo.Products AS p
WHERE NOT EXISTS (
SELECT 1 FROM dbo.OrderItems AS i
WHERE i.ProductID = p.ProductID AND i.OrderID BETWEEN 1 AND 5
)
ORDER BY p.ProductID;Read it step by step
- For each product, the inner query looks for a line in Orders 1–5.
- NOT EXISTS keeps products with no such line; SELECT 1 is only a placeholder because existence is what matters.
- The product ID is unique, so each retained product appears once.
Check the result
| ProductID | ProductName |
|---|---|
| 11 | Keyboard |
| 12 | Cable Pack |
| 13 | Desk Chair |
| 14 | Side Table |
| 15 | Shelf Unit |
This says nothing about orders after ID 5.
Practice
Return products that do appear in OrderItems for Orders 1–5.
Check your answer and expected result
Reveal answer
sql
SELECT p.ProductID, p.ProductName
FROM dbo.Products AS p
WHERE EXISTS (
SELECT 1 FROM dbo.OrderItems AS i
WHERE i.ProductID = p.ProductID AND i.OrderID BETWEEN 1 AND 5
)
ORDER BY p.ProductID;| ProductID | ProductName |
|---|---|
| 1 | Laptop Stand |
| 2 | USB-C Dock |
| 3 | Webcam |
| 4 | Notebook |
| 5 | Pen Set |
| 6 | Desk Lamp |
| 7 | Headphones |
| 8 | Speaker |
| 9 | Microphone |
| 10 | Wireless Mouse |
EXISTS retains a product once even if several matching order lines exist.
Your progress
Reveal the check answer or reach the end to complete this lesson.