AND, OR, and NOT
Logical Operators: AND, OR, and NOT
Definition: Logical operators allow you to create more complex filters by combining two or more conditions or by reversing a condition. They are essential for narrowing down search results with high precision.
Usage: Beginner SQL course outlines introduce these operators early in filtering lessons because real-world data requests often involve multiple requirements, such as "Find active users (AND) who live in a specific region."
1. The AND Operator
The AND operator displays a record if all conditions separated by it are TRUE.
SELECT * FROM students WHERE age >= 18 AND city = 'Mysuru';
Effect: Only students who are at least 18 years old AND live in Mysuru will appear.
2. The OR Operator
The OR operator displays a record if any of the conditions separated by it are TRUE.
SELECT * FROM students WHERE city = 'Mysuru' OR city = 'Hassan';
Effect: Students from either Mysuru or Hassan will appear.
3. The NOT Operator
The NOT operator displays a record if the condition(s) is NOT TRUE (it reverses the logic).
SELECT * FROM students WHERE NOT age < 20;
Effect: This returns all students except those younger than 20 (functionally the same as age >= 20).
Operator Truth Table
| Operator | Requirement to show Row |
|---|---|
| AND | Every single condition must be met. |
| OR | At least one condition must be met. |
| NOT | The condition must be false. |
Key Notes
- Order of Precedence: When you use multiple operators (e.g.,
ANDandORin the same line), SQL processesANDbeforeOR. Use parentheses( )to force a different order and make your code more readable. - Combining NOT: You will often see
NOTused with other keywords, such asWHERE city NOT IN ('Bengaluru', 'Mysuru')orWHERE name NOT LIKE 'A%'. - Readability: For simple logic,
NOT age < 20is less readable thanage >= 20. Only useNOTwhen it makes the intent of the query clearer.
🏋️ Test Yourself With Exercises
Take our quiz on AND, OR, and NOT to test your knowledge.
Browse Quizzes »