Logical Operators
Logical operators allow you to combine multiple conditions in a SQL query using the WHERE
clause. This helps you make your data filters more precise and powerful.
Main Logical Operators
Operator | Description | Example |
---|---|---|
AND | All conditions must be true | membership_type = 'student' AND has_overdue_books = 'no' |
OR | At least one condition must be true | membership_type = 'guest' OR number_of_books > 3 |
NOT | Reverses or excludes a condition | NOT has_overdue_books = 'yes' |
AND Operator Example
The AND
operator is used to filter rows where all conditions must be true.
SELECT name, membership_type FROM library_members WHERE membership_type = 'student' AND has_overdue_books = 'no';
This query returns students who do not have any overdue books.
OR Operator Example
The OR
operator is used to filter rows where at least one condition must be true.
SELECT name, number_of_books FROM library_members WHERE membership_type = 'guest' OR number_of_books > 3;
This query returns either guests or anyone with more than 3 books checked out.
NOT Operator Example
The NOT
operator is used to filter rows where the condition is false.
SELECT name FROM library_members WHERE NOT has_overdue_books = 'yes';
This query returns only members who do not have overdue books.
Why It Matters
Logical operators are critical when:
- Applying multiple filters to a dataset
- Handling exceptions and special cases
- Writing queries that mirror real-world logic
They give you precise control over what data you retrieve.
What’s Next?
In the next lesson, you’ll learn how to sort and limit results using ORDER BY
and LIMIT
.
What does the following query do?
SELECT name FROM library_members WHERE NOT has_overdue_books = 'yes';
Returns only members who have overdue books
Returns nothing
Excludes members with overdue books
Shows members with no books borrowed
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Tables
Execution Result