Skip to main content
Practice

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

OperatorDescriptionExample
ANDAll conditions must be truemembership_type = 'student' AND has_overdue_books = 'no'
ORAt least one condition must be truemembership_type = 'guest' OR number_of_books > 3
NOTReverses or excludes a conditionNOT has_overdue_books = 'yes'

AND Operator Example

The AND operator is used to filter rows where all conditions must be true.

Filter: Students with no overdue books
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.

Filter: Guests or those with many books
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.

Filter: Exclude members with overdue books
SELECT name
FROM library_members
WHERE NOT has_overdue_books = 'yes';

This query returns only members who do not have overdue books.


Why logical operators matter

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.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.