Logical Operators
Overview
Logical operators connect multiple filter predicates inside a WHERE clause, enabling highly precise multi-conditional queries.
Learning Objectives
- Combine filters using
AND,OR, andNOToperators. - Analyze operator precedence rules and how to override them with parentheses.
- Master Boolean truth tables in SQL three-valued logic.
Detailed Concept Explanation
SQL uses three-valued logic: TRUE, FALSE, and NULL (unknown).
AND: ReturnsTRUEonly if both conditions evaluate toTRUE.OR: ReturnsTRUEif at least one condition evaluates toTRUE.NOT: Reverses the boolean outcome of a condition.
Operator Precedence
SQL evaluates logical operators in the order of NOT, then AND, then OR. To override this order and prevent logical bugs, wrap conditions inside parentheses ().
Code Examples
SQL
-- Filter active users located in either the North or West regions
-- Parentheses are vital here to group the OR regions before applying AND status
SELECT name, region, status
FROM users
WHERE status = 'Active'
AND (region = 'North' OR region = 'West');
-- Negate a criteria using NOT
SELECT product_name
FROM products
WHERE NOT category = 'Electronics';
Best Practices
- Parenthesise Complex Criteria: Always use parentheses when mixing
ANDandORto guarantee predictable execution logic. - Readability: Format multi-line predicates with consistent indentation so that compound rules are visually clear.
Interview Perspective
Warning
Common Pitfall: Mixing AND/OR without Parentheses
Consider WHERE status = 'A' AND region = 'US' OR region = 'CA'. Due to precedence, this evaluates as (status = 'A' AND region = 'US') OR region = 'CA'. It will return active US users AND all Canadian users regardless of status. Fix this with: status = 'A' AND (region = 'US' OR region = 'CA').
Interactive Challenges
Summary
Logical operators AND, OR, and NOT build complex filters. Remember to use parentheses to secure evaluation precedence.