AND / OR / NOT
Logical operators used to combine multiple conditions for filtering rows. Use parentheses carefully to control the order of evaluation.
Syntax
-- AND: Returns rows that satisfy both conditions. SELECT column FROM table WHERE condition1 AND condition2; -- OR: Returns rows that satisfy either condition. SELECT column FROM table WHERE condition1 OR condition2; -- NOT: Negates a condition. SELECT column FROM table WHERE NOT condition; -- Use parentheses to make precedence explicit. SELECT column FROM table WHERE condition1 AND (condition2 OR condition3);
Operators
| Operator | Description |
|---|---|
| AND | Returns true only when both the left and right conditions are true. |
| OR | Returns true when at least one of the left or right conditions is true. |
| NOT | Reverses the truth value of the following condition. |
| ( ) | Evaluates the enclosed conditions first. Use parentheses to enforce the intended order, since AND has higher precedence than OR. |
Sample Code
-- Retrieve employees in the Sales department with a salary of 300,000 or more. SELECT name, department, salary FROM employees WHERE department = 'Sales' AND salary >= 300000; -- Retrieve employees in either the Sales or Engineering department. SELECT name, department FROM employees WHERE department = 'Sales' OR department = 'Engineering'; -- Retrieve employees who are NOT in the Administration department. SELECT name, department FROM employees WHERE NOT department = 'Administration'; -- Control precedence with parentheses. -- Retrieve "Engineering employees" OR "Sales employees with salary >= 300,000". SELECT name, department, salary FROM employees WHERE department = 'Engineering' OR (department = 'Sales' AND salary >= 300000);
Result
-- Result of: SELECT name, department, salary FROM employees -- WHERE department = 'Engineering' OR (department = 'Sales' AND salary >= 300000); -- +----------+-------------+--------+ -- | name | department | salary | -- +----------+-------------+--------+ -- | Tanaka | Sales | 320000 | -- | Suzuki | Engineering | 280000 | -- | Yamada | Engineering | 300000 | -- +----------+-------------+--------+
Database Compatibility
The syntax and precedence rules for AND, OR, and NOT are consistent across all major databases.
SELECT name, department, salary FROM employees WHERE department = 'Engineering' OR (department = 'Sales' AND salary >= 300000);
Notes
SQL logical operators follow this precedence order: NOT → AND → OR. For example, A OR B AND C is evaluated as A OR (B AND C). Use parentheses freely in complex conditions to avoid unintended results.
When listing multiple OR conditions on the same column, the IN clause is a more readable alternative. For example, department = 'Sales' OR department = 'Engineering' is equivalent to department IN ('Sales', 'Engineering').
AND, OR, and NOT can be used not only in the WHERE clause, but also in the HAVING clause and elsewhere.
If you find any errors or copyright issues, please contact us.