Filtering and sorting
AND, OR, and NOT
Combine conditions while making precedence explicit.
Lesson 13 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. Real questions often have several conditions. Here the goal is North-region customers in Leeds or York, excluding North customers in other cities.
Run the example
SELECT CustomerID, City, Region
FROM dbo.Customers
WHERE Region = N'North'
AND (City = N'Leeds' OR City = N'York')
ORDER BY CustomerID;Read it step by step
- Region = N'North' must be TRUE for every returned row because it is joined to the city group with AND.
- The parentheses group City = N'Leeds' OR City = N'York'. A row passes that group when either city matches.
- AND has higher precedence than OR. The parentheses make the intended grouping obvious to readers and prevent a different meaning if the expression grows.
Check the result
| CustomerID | City | Region |
|---|---|---|
| 5 | Leeds | North |
| 7 | York | North |
| 12 | Leeds | North |
| 16 | York | North |
The four rows meet both the region rule and the grouped city rule. NOT can reverse a condition, for example NOT (Region = N'North'), but a comparison involving NULL may be UNKNOWN rather than TRUE or FALSE.
Practice
Find active products in category 1 or 3. Include parentheses so the active condition applies to both categories.
Check your answer and expected result
Reveal answer
SELECT ProductID, CategoryID FROM dbo.Products WHERE IsActive = 1 AND (CategoryID = 1 OR CategoryID = 3) ORDER BY ProductID;| ProductID | CategoryID |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 7 | 3 |
| 8 | 3 |
| 9 | 3 |
IDs 1, 2, 3, 7, 8, and 9 qualify.
Your progress
Reveal the check answer or reach the end to complete this lesson.