SQL AND, OR, NOT Operators
beginnerfiltering
2 min read
What are AND, OR, NOT?
These logical operators combine multiple conditions in a WHERE clause:
AND— Both conditions must be true.OR— At least one condition must be true.NOT— Negates a condition.
Syntax
SELECT * FROM table_name
WHERE condition1 AND condition2;
SELECT * FROM table_name
WHERE condition1 OR condition2;
SELECT * FROM table_name
WHERE NOT condition;When to Use
- Requiring multiple filters simultaneously (AND)
- Accepting any of several alternatives (OR)
- Excluding a specific set of rows (NOT)
Key Points
- Precedence —
ANDbinds tighter thanOR. Use parentheses to make intent clear:WHERE (a OR b) AND c. - Short-circuit — PostgreSQL may skip evaluating the second condition if the first determines the result.
- NOT with IN —
WHERE NOT IN (...)excludes a list of values. - NOT with LIKE —
WHERE name NOT LIKE 'A%'excludes names starting with A. - Readability — Complex conditions benefit from parentheses even when not strictly necessary.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
SQL AND, OR, NOT Operators Challenge
Write a query that find students who are in grade A and older than 20.
Expected result
Only students with grade A who are also older than 20.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What are AND, OR, NOT?
Initializing database...Each run starts from fresh sample data.
More Examples
OR operator
Find products in Electronics or Home category.
Initializing database...Each run starts from fresh sample data.
NOT operator
Find all employees not in the Sales department.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the precedence of AND and OR?
AND is evaluated before OR. To change the order, use parentheses: WHERE (a OR b) AND c evaluates OR first.
Can I chain multiple AND or OR conditions?
Yes. You can use as many AND and OR operators as needed. For long lists of OR conditions, consider using the IN operator instead.