Skip to content
Back to 50 Concepts
Topic 12 of 50query-executionBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

AND, OR, NOT Logic Visual Simulator

Step 1 of 3
SQL>SELECT * FROM accounts WHERE status = 'active' AND (plan = 'enterprise' OR balance > 10000);Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for AND, OR, NOT Logic
SQL Input

Initiating AND, OR, NOT Logic

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Electrical Circuit: AND is components in series (all must connect); OR is components in parallel (any path connects).

4. Real-World Example

Filtering customers who are either premium members OR active users located in the EU.

Users
nameis_premiumis_activeregion
AlicetruefalseUS
BobfalsetrueEU
CharliefalsefalseEU
Relational walkthrough: Without parentheses, AND binds tighter than OR, leading to unintended filter results.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Parentheses for logical grouping
SELECT name, is_premium, region
FROM users
WHERE is_premium = TRUE OR (is_active = TRUE AND region = 'EU');
Always use explicit parentheses when mixing AND with OR.
Step 2: Negation with NOT
SELECT name FROM users WHERE NOT (region = 'US' OR region = 'CA');
Equivalent to region != 'US' AND region != 'CA'.

6. Important Rules & Behaviors

RuleBehavioral Explanation
AND Binds Tighter Than ORCondition A OR B AND C is evaluated as A OR (B AND C).
Short-CircuitingMost SQL optimizers short-circuit boolean conditions for efficiency, but order of evaluation is not guaranteed.
De Morgan’s LawsNOT (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 OROR 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');
Caution: Whenever you mix AND with OR, parentheses are mandatory for defensive coding.

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

Scenario Question:

How does SQL evaluate the expression: TRUE OR FALSE AND FALSE?

Select your answer: