Logical Operators
Logical operators are used to combine or negate boolean expressions. They are essential for building complex conditions in WHERE clauses, CASE expressions, and other conditional constructs.
Supported Operators
Operator | Description |
|---|---|
| Returns |
| Returns |
| Negates a boolean expression |
Syntax
boolean_expression AND boolean_expression boolean_expression OR boolean_expression NOT boolean_expression
Truth Tables
AND Operator
A | B | A AND B |
|---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
TRUE | NULL | NULL |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
FALSE | NULL | FALSE |
NULL | TRUE | NULL |
NULL | FALSE | FALSE |
NULL | NULL | NULL |
OR Operator
A | B | A OR B |
|---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
TRUE | NULL | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
FALSE | NULL | NULL |
NULL | TRUE | TRUE |
NULL | FALSE | NULL |
NULL | NULL | NULL |
NOT Operator
A | NOT A |
|---|---|
TRUE | FALSE |
FALSE | TRUE |
NULL | NULL |
Operator Precedence
NOT(highest precedence)ANDOR(lowest precedence)
Use parentheses to override default precedence when needed.
Examples
AND Operator
-- Example 1: Both conditions must be true > SELECT * FROM employees WHERE department_id = 10 AND salary > 50000; -- Example 2: Multiple AND conditions > SELECT * FROM orders WHERE status = 'completed' AND amount > 100 AND order_date >= '2025-01-01';
OR Operator
-- Example 3: Either condition can be true > SELECT * FROM products WHERE category = 'Electronics' OR category = 'Appliances'; -- Example 4: Combining OR with other conditions > SELECT * FROM employees WHERE (department_id = 10 OR department_id = 20) AND salary > 50000;
NOT Operator
-- Example 5: Negate a condition
> SELECT * FROM orders
WHERE NOT status = 'cancelled';
-- Example 6: NOT with IN operator
> SELECT * FROM products
WHERE NOT category IN ('Discontinued', 'Archived');
-- Example 7: NOT with LIKE operator
> SELECT * FROM employees
WHERE NOT name LIKE 'Test%';
Complex Expressions
-- Example 8: Combining AND, OR, and NOT with parentheses
> SELECT * FROM orders
WHERE (status = 'pending' OR status = 'processing')
AND NOT customer_id IS NULL
AND amount > 0;