# 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.
2. Explain Like I'm 5
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 TracePredicate Filter Evaluation Pipeline
SELECT * FROM employees WHERE salary > 60000 AND status = 'active';Active InputStep 1: Stream Tuples from Table
Row 1
Row 2
Row 3
Candidate rows enter the filter engine one by one.
4. Real-World Example
Filtering active subscribers whose account balance is greater than zero.
| id | user_id | status | balance |
|---|---|---|---|
| 1 | 101 | active | 45.00 |
| 2 | 102 | suspended | 0.00 |
| 3 | 103 | active | 120.00 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT id, user_id, balance FROM accounts WHERE status = 'active' AND balance > 0.00;
SELECT id, user_id FROM accounts WHERE (status = 'active' OR status = 'trial') AND balance >= 10.00;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Boolean Evaluation | WHERE returns rows where the condition evaluates strictly to TRUE (discarding FALSE and UNKNOWN). |
| Sargability | Predicates must be Search Argument Able (sargable) so the optimizer can traverse B-Tree index pages directly. |
| Aggregates Forbidden | Aggregate functions (like COUNT or SUM) cannot be used in WHERE; use HAVING instead. |
| SARGable predicate requirement | Predicates must compare raw indexed columns to constants; wrapping columns in functions prevents index scans. |
| Short-circuit evaluation order | Engines 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';
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) = 2026 | WHERE 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 > 100 | WHERE 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
Which WHERE clause is sargable and can efficiently utilize a standard B-Tree index on created_at?