AND, OR, NOT Operators
So far, we have used the WHERE clause to filter data using a single condition. In real-world scenarios, one condition is usually not enough.
SQL provides logical operators — AND, OR, and NOT — to combine multiple conditions in a powerful and flexible way.
Why Do We Need Logical Operators?
Imagine you want to:
- Find employees who work in IT and earn more than 70,000
- Find employees who work in HR or Finance
- Exclude employees from a specific department
These scenarios are impossible with a single condition. That’s where logical operators come in.
The AND Operator
The AND operator returns rows only when all conditions are true.
Syntax:
SELECT * FROM table_name WHERE condition1 AND condition2;
Example: Employees in IT department earning more than 70,000.
SELECT name, department, salary FROM employees WHERE department = 'IT' AND salary > 70000;
Only employees who satisfy both conditions will be returned.
The OR Operator
The OR operator returns rows when at least one condition is true.
Syntax:
SELECT * FROM table_name WHERE condition1 OR condition2;
Example: Employees working in HR or Finance.
SELECT name, department FROM employees WHERE department = 'HR' OR department = 'Finance';
Rows matching either condition will appear in the result.
The NOT Operator
The NOT operator is used to exclude rows that match a condition.
Syntax:
SELECT * FROM table_name WHERE NOT condition;
Example: Employees not working in HR.
SELECT name, department FROM employees WHERE NOT department = 'HR';
This query removes all HR employees from the result.
Combining AND, OR, NOT
Logical operators can be combined to build complex conditions.
Example: Employees in IT department earning more than 70,000 or employees in Finance.
SELECT name, department, salary FROM employees WHERE (department = 'IT' AND salary > 70000) OR department = 'Finance';
Parentheses () control the order of evaluation and
make the logic clear.
Truth Table (Simple Logic)
| Condition A | Condition B | A AND B | A OR B |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
Common Beginner Mistakes
- Forgetting parentheses in complex conditions
- Using AND when OR is needed (or vice versa)
- Assuming NOT removes columns instead of rows
When queries behave unexpectedly, always re-check your logic.
What’s Next?
In the next lesson, we will learn how to
sort query results using the
ORDER BY clause.