Filtering and sorting
IN and BETWEEN
Express membership and inclusive ranges clearly.
Lesson 14 of 84
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
This lesson uses DDI_SQL_Training dataset version 1.0.0 on SQL Server 2019 or later. Repeated OR conditions can be hard to read. IN expresses a small list of allowed values; BETWEEN expresses a range with both endpoints included.
Run the example
SELECT OrderID, OrderDate
FROM dbo.Orders
WHERE OrderID IN (1, 2, 3)
ORDER BY OrderID;Read it step by step
- OrderID IN (1, 2, 3) means OrderID = 1 OR OrderID = 2 OR OrderID = 3.
- The SELECT list returns each chosen order’s ID and date. ORDER BY OrderID displays them in ID order.
- For a range, CustomerID BETWEEN 3 AND 5 means CustomerID >= 3 AND CustomerID <= 5. Both 3 and 5 qualify.
Check the result
| OrderID | OrderDate |
|---|---|
| 1 | 2023-01-02 |
| 2 | 2023-01-03 |
| 3 | 2023-01-04 |
The output has exactly three rows because those three OrderID values exist. IN does not return one row per listed value if a value is absent, and it does not duplicate an order when a value is listed twice.
Practice
Find customers whose CustomerID is between 3 and 5, inclusive. Which IDs appear?
Check your answer and expected result
Reveal answer
SELECT CustomerID, FirstName FROM dbo.Customers WHERE CustomerID BETWEEN 3 AND 5 ORDER BY CustomerID;| CustomerID | FirstName |
|---|---|
| 3 | Leo |
| 4 | Isla |
| 5 | Ravi |
IDs 3, 4, and 5 appear.
Your progress
Reveal the check answer or reach the end to complete this lesson.