Filtering and sorting
WHERE and comparison operators
Filter rows using comparisons with correctly typed values.
Lesson 12 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. The full Customers table has 20 rows. WHERE narrows a query to rows that meet a condition, such as customers in London.
Run the example
SELECT CustomerID, FirstName, City
FROM dbo.Customers
WHERE City = N'London'
ORDER BY CustomerID;Read it step by step
- FROM dbo.Customers supplies the source rows. WHERE City = N'London' tests each City value for equality with the Unicode text London.
- Only rows for which the comparison is TRUE remain. SELECT then returns their ID, name, and city.
- ORDER BY CustomerID makes the five matching rows appear in a predictable order. Other comparisons include <, <=, >, >=, and <>.
Check the result
| CustomerID | FirstName | City |
|---|---|---|
| 1 | Alex | London |
| 4 | Isla | London |
| 10 | Ada | London |
| 15 | Arjun | London |
| 20 | Imani | London |
Five rows pass the filter; the other 15 do not appear. The predicate does not change any customer record. Numeric comparisons work the same way: ListPrice > 100 selects products whose price exceeds, rather than equals, 100.
Practice
Return products with ListPrice greater than 100, ordered by ProductID. How many qualify?
Check your answer and expected result
Reveal answer
SELECT ProductID, ProductName, ListPrice FROM dbo.Products WHERE ListPrice > 100 ORDER BY ProductID;| ProductID | ProductName | ListPrice |
|---|---|---|
| 2 | USB-C Dock | 129.00 |
| 9 | Microphone | 119.00 |
| 13 | Desk Chair | 189.00 |
| 15 | Shelf Unit | 149.00 |
Four products qualify: IDs 2, 9, 13, and 15.
Your progress
Reveal the check answer or reach the end to complete this lesson.