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

# Topic 7: WHERE Clause

Filtering tuples using comparison operators, predicate sargability, and avoiding unindexed function scans.

1. Definition

The WHERE clause specifies search conditions (predicates) that filter rows before any grouping or aggregation takes place.

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

2. Explain Like I'm 5

Intuitive mental model for beginners

WHERE is a security guard at a club door. Only guests with valid IDs and correct dress codes are allowed inside; everyone else is filtered out immediately.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

Predicate Filter Evaluation Pipeline

Step 1 of 3
SQL>SELECT * FROM employees WHERE salary > 60000 AND status = 'active';Active Input

Step 1: Stream Tuples from Table

Engine Action: Fetch raw rows from heap or index
Alice ($75k, active)

Row 1

Bob ($50k, active)

Row 2

Charlie ($90k, inactive)

Row 3

How the Database Executes This:

Candidate rows enter the filter engine one by one.

4. Real-World Example

Filtering active subscribers whose account balance is greater than zero.

Accounts
iduser_idstatusbalance
1101active45.00
2102suspended0.00
3103active120.00
Relational walkthrough: WHERE filters out row 2 because its status is not active.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Filtering with comparison operators
SELECT id, user_id, balance
FROM accounts
WHERE status = 'active' AND balance > 0.00;
Only rows where both conditions evaluate to TRUE are returned.
Step 2: Checking multiple criteria with parentheses
SELECT id, user_id
FROM accounts
WHERE (status = 'active' OR status = 'trial')
  AND balance >= 10.00;
Parentheses clarify evaluation order when mixing AND and OR.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Boolean EvaluationWHERE returns rows where the condition evaluates strictly to TRUE (discarding FALSE and UNKNOWN).
SargabilityPredicates must be Search Argument Able (sargable) so the optimizer can traverse B-Tree index pages directly.
Aggregates ForbiddenAggregate functions (like COUNT or SUM) cannot be used in WHERE; use HAVING instead.
SARGable predicate requirementPredicates must compare raw indexed columns to constants; wrapping columns in functions prevents index scans.
Short-circuit evaluation orderEngines may reorder WHERE conditions based on selectivity costs rather than left-to-right code order.

7. Deep Dive: Sargability and B-Tree Index Invalidation

Wrapping an indexed column inside a function prevents the database from using a B-Tree index, forcing a full sequential scan of the table.

-- Non-sargable (SLOW - scans entire table):
WHERE EXTRACT(YEAR FROM created_at) = 2026;

-- Sargable (FAST - uses B-Tree range scan):
WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01';
Caution: Never apply functions to column names on the left side of comparison operators in WHERE.

8. Advantages & Disadvantages

Advantages

  • •Filters unneeded rows before expensive grouping, sorting, or joins.
  • •Allows B-Tree index scans to jump directly to matching leaf pages.
  • •Reduces working memory (work_mem) consumption.

Disadvantages & Trade-offs

  • •Poorly structured non-sargable predicates degrade queries into slow full table scans.

9. Common Interview Questions

Q1.What does SARGable mean in SQL, and why is it critical for performance?

SARGable stands for "Search Argument Able". A predicate is SARGable if the database engine can use a B-Tree index to perform a direct index seek (O(log N)) rather than scanning every row in the table (O(N)). Wrapping an indexed column inside a function (e.g. WHERE YEAR(created_at) = 2026) destroys SARGability because the B-Tree keys contain raw dates, not computed years.

Non-SARGable (Forces Full Table Scan)SARGable Equivalent (Uses Index Seek)
WHERE YEAR(created_at) = 2026WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'
WHERE LOWER(email) = 'alice@test.com'WHERE email = 'alice@test.com' (or create functional index)
WHERE price * 1.10 > 100WHERE price > 100 / 1.10
WHERE name LIKE '%son'Full Scan (leading wildcard cannot navigate B-Tree)

Q2.How does the Cost-Based Optimizer estimate selectivity for WHERE predicates?

The optimizer consults system statistics tables (e.g. pg_statistic / pg_stats in PostgreSQL) populated by ANALYZE. It stores: null_frac (fraction of NULLs), n_distinct (count of unique values), most_common_vals (MCV array with frequencies), and histogram_bounds (quantiles dividing non-MCV values into buckets). The optimizer interpolates histogram buckets to estimate the row count and pick the cheapest execution plan.

Q3.Does the SQL engine always evaluate WHERE conditions from left to right?

No. SQL is declarative: the engine is free to evaluate predicates in whatever order it determines to be most efficient. The optimizer typically evaluates cheap, highly-selective predicates first (like integer equality) before evaluating expensive operations (like regex matches or subqueries), regardless of how they are written in the query.

Q4.What is the difference between filtering in WHERE vs filtering in HAVING?

WHERE filters individual row tuples BEFORE grouping and aggregation occur. HAVING filters grouped rows AFTER the GROUP BY clause and aggregate computations have executed. Aggregation functions (e.g. SUM(), COUNT()) are forbidden in WHERE clauses because aggregate values do not exist until grouping completes.

Q5.How does Three-Valued Logic (3VL) affect the WHERE clause with NULLs?

In SQL, the WHERE clause only outputs rows where the predicate evaluates to TRUE. If a predicate evaluates to FALSE or UNKNOWN (which happens when comparing with NULL, e.g. NULL = 5), the row is discarded. This means WHERE col = 5 and WHERE col != 5 will BOTH exclude rows where col IS NULL.

10. Interview-Ready Answer

“The WHERE clause filters rows using search predicates prior to grouping. High-performance queries keep predicates sargable by comparing isolated column names against constants, allowing B-Tree indexes to perform logarithmic point lookups.”

11. Quick Test

Scenario Question:

Which WHERE clause is sargable and can efficiently utilize a standard B-Tree index on created_at?

Select your answer: