# Topic 12: AND, OR, NOT Logic
Combining boolean predicates, operator precedence (AND before OR), De Morgan’s laws, and short-circuit evaluation.
1. Definition
AND, OR, and NOT are logical operators used in WHERE and HAVING clauses to join or negate search predicates.
2. Explain Like I'm 5
AND is picky (both must be true). OR is generous (at least one must be true). NOT flips the switch (true becomes false).
3. Animation & Visual Simulation
Interactive Engine TraceAND, OR, NOT Logic Visual Simulator
SELECT * FROM accounts
WHERE status = 'active' AND (plan = 'enterprise' OR balance > 10000);Active InputStep 1: Input & Parsing Stage
Initiating AND, OR, NOT Logic
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Filtering customers who are either premium members OR active users located in the EU.
| name | is_premium | is_active | region |
|---|---|---|---|
| Alice | true | false | US |
| Bob | false | true | EU |
| Charlie | false | false | EU |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT name, is_premium, region FROM users WHERE is_premium = TRUE OR (is_active = TRUE AND region = 'EU');
SELECT name FROM users WHERE NOT (region = 'US' OR region = 'CA');
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| AND Binds Tighter Than OR | Condition A OR B AND C is evaluated as A OR (B AND C). |
| Short-Circuiting | Most SQL optimizers short-circuit boolean conditions for efficiency, but order of evaluation is not guaranteed. |
| De Morgan’s Laws | NOT (A AND B) equals (NOT A) OR (NOT B); NOT (A OR B) equals (NOT A) AND (NOT B). |
| Operator precedence (AND before OR) | AND has strictly higher precedence than OR; always use explicit parentheses when combining them. |
| Index union scan on OR | OR conditions on different columns require BitmapOr index scans or full table scans if one column is unindexed. |
7. Deep Dive: The Dangerous "AND Binds Tighter Than OR" Production Bug
Developers frequently write: WHERE status = "active" AND country = "US" OR country = "CA". Because AND takes precedence, this executes as (active AND US) OR CA, accidentally leaking all inactive Canadian accounts!
-- DANGEROUS BUG (returns inactive Canadians!): WHERE status = 'active' AND country = 'US' OR country = 'CA'; -- FIXED WITH PARENTHESES: WHERE status = 'active' AND (country = 'US' OR country = 'CA');
8. Advantages & Disadvantages
Advantages
- •Enables precise multi-dimensional filtering.
- •Allows clean expression of complex business rules.
Disadvantages & Trade-offs
- •Unparenthesized expressions create catastrophic data leak bugs.
9. Common Interview Questions
Q1.How does an OR clause affect index utilization compared to an AND clause?
An AND clause on indexed columns (col1 = 1 AND col2 = 2) can utilize a single composite B-Tree index or perform a fast index intersection. An OR clause on different columns (col1 = 1 OR col2 = 2) requires the engine to either perform a BitmapOr scan (scanning index 1, scanning index 2, combining bitmaps in memory, and fetching heap pages) or fall back to a full table scan if either column lacks an index.
Q2.What are De Morgan’s Laws and how do you apply them to simplify complex SQL predicates?
De Morgan’s Laws state: 1. NOT (A AND B) = (NOT A) OR (NOT B), and 2. NOT (A OR B) = (NOT A) AND (NOT B). In SQL performance tuning, converting negated complex groupings into positive indexed comparisons often allows the optimizer to use B-Tree indexes instead of scanning the full table.
Q3.What is short-circuit evaluation in boolean expressions and can you rely on it in SQL?
In procedural languages (like C/Python), if the first operand of AND is FALSE, the second operand is never evaluated. In SQL, the SQL standard does NOT guarantee short-circuit evaluation order: the Cost-Based Optimizer is free to evaluate expressions in whatever order is cheapest. For example, in WHERE x > 0 AND 100 / x > 2, the engine might evaluate 100 / x first and crash with a division-by-zero error. Use CASE WHEN for guaranteed evaluation order.
Q4.How does NOT interact with B-Tree indexes?
B-Tree indexes are sorted structures optimized for finding specific keys or bounded ranges. The NOT operator (e.g. WHERE status != 'active') is non-SARGable because it asks for everything EXCEPT a value. Unless the table is partitioned or a partial index is specifically created, the optimizer almost always falls back to a Sequential Scan.
Q5.How do you optimize a slow OR query across two indexed columns?
A query like SELECT * FROM users WHERE email = 'x' OR phone = 'y' can be slow if the optimizer struggles with BitmapOr. You can optimize it by rewriting it as a UNION ALL with an anti-join or deduplication: (SELECT * FROM users WHERE email = 'x') UNION (SELECT * FROM users WHERE phone = 'y'); This allows each branch to perform an ultra-fast O(log N) index seek.
10. Interview-Ready Answer
“AND takes precedence over OR in SQL boolean logic. To prevent unintentional security and data filtering bugs, always wrap OR clauses inside parentheses when combined with AND.”
11. Quick Test
How does SQL evaluate the expression: TRUE OR FALSE AND FALSE?