Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 133/ 160
07. Indexing, Query Optimization & Performance Tuning

SARGable Queries (Writing Index-Friendly WHERE Clauses)

Write predicates the optimizer can seek with indexes (Search ARGument Able).

IntermediateSARGable · Seek · Predicate3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Leave the indexed column alone in the WHERE clause, and put any calculation on the other side, so the database can jump straight to the rows.

Think of it like…

A dictionary sorted by word: finding words starting with "pre" is a quick jump. Finding words whose *third* letter is "e" means reading every page, even though the dictionary is sorted.

Where you’ve seen it

WHERE DATE(created_at) = '2026-11-19' scans every order. WHERE created_at >= '2026-11-19' AND created_at < '2026-11-20' means the same thing and uses the index on created_at.

Words you’ll hear

SARGable
A predicate shape the optimizer can turn into an index seek or range scan.
Index seek
Jumping straight to matching index entries instead of scanning.
Expression index
An index on a computed value, such as LOWER(email), so that expression becomes searchable.
Implicit conversion
The database silently casting a column to compare it with a different type, which can disable the index.

Visual diagram

Loading interactive diagram

Theory & example queries

Shapes that break index use

A B-tree index stores the column's values in sorted order. It can answer questions about those values directly (=, <, >, BETWEEN, IN, prefix LIKE 'abc%'), but not about a transformed version of them. LOWER(email) = ?, price * 1.18 > 100, created_at + interval '1 day' > now() and COALESCE(status, 'new') = 'new' all apply something to the column first, so the index can't be searched.

Other common culprits: a leading wildcard (LIKE '%gmail.com'), implicit type conversions (in MySQL, comparing a VARCHAR phone column with a number casts every row), and wrapping columns in functions inside joins.

Moving arithmetic to the constant side

WHERE price * 1.18 > 1180 can't use an index on price; WHERE price > 1000 (1180 ÷ 1.18) can.

Key takeaway: If the column is inside a function or calculation, the index can't help.

How to fix them

Rewrite the condition so the bare column is compared with a value: date functions become ranges, arithmetic moves to the other side, and col + 1 = 5 becomes col = 4. Ranges written as >= start AND < next_start also avoid off-by-one errors with timestamps.

When the transformation is part of the logic, such as case-insensitive email lookup, index the expression itself: CREATE INDEX ON users (LOWER(email)), then query with exactly the same expression. For suffix or substring search, use a trigram index (pg_trgm) or full-text search rather than LIKE '%…%'.

Case-insensitive lookup that uses an indexQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE INDEX idx_users_email_lower ON users (LOWER(email));
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/1
query.sql
1SELECT2  *3FROM4  users5WHERE6  LOWER(email) = LOWER($1);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative lookup result1 sample row
Representative lookup result
idemailname
101ada@example.comAda Patel

Note: Assumes $1 is case-insensitively equal to "ada@example.com" and the users table has this one match.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then

Key takeaway: Rewrite to a bare column, or index the exact expression you query.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1EXPLAIN

Spot the scan

Run EXPLAIN on the slow query. A Seq Scan with a Filter on an indexed column is the classic sign of a non-SARGable condition.

Focus at this step

Seq Scan … Filter: (date(created_at) = …)

What to watch at this step
Look for
functions in Filter
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A condition is SARGable (Search ARGument-able) when the database can use an index to seek straight to the matching rows. That usually means the indexed column stands alone on one side of the comparison: created_at >= '2026-01-01' is SARGable, while YEAR(created_at) = 2026 isn't, because the function hides the column from the index.

Why it matters: It's the most common reason an index exists but the query still does a full scan. Rewriting a single WHERE clause can turn a 10-second query into a 10-millisecond one with no new index, which is why interviewers love "why isn't this query using my index?".

When to reach for it

  • Date filters on timestamp columns
  • Case-insensitive lookups on emails and usernames
  • Any query where EXPLAIN shows a Seq Scan despite an index

When to avoid or be careful

  • Functions on indexed columns in WHERE and JOIN conditions
  • Leading wildcards in LIKE on large tables
  • Comparing columns with values of a different type

Fixing a non-SARGable condition

Rewrite the predicate
Best for: Date functions, arithmetic, simple casts

Strengths: Uses the existing index; no new objects.

Watch out: The query has to be written carefully, especially date boundaries.

Expression index
Best for: Transformations that are part of the logic, like LOWER(email)

Strengths: Makes the exact expression searchable.

Watch out: Only helps queries that use the identical expression; another index to maintain.

Trigram or full-text index
Best for: Substring and suffix search ('%term%')

Strengths: Fast fuzzy and contains-style search.

Watch out: Larger indexes and different query syntax.

Interview signals & numbers to know

When this topic comes up

  • “I have an index but the query is still slow”
  • “Why isn't my index being used?”
  • Seq Scan with a Filter on an indexed column
  • WHERE YEAR(date) = …
  • LIKE '%…'

Benchmarks & rules of thumb

>= start AND < next -
the safe pattern for date ranges
'abc%' -
can use a B-tree; '%abc' can't
1 expression -
per expression index

Common mistakes & follow-ups

Common interview mistakes

  • Filtering with DATE(created_at) = '…' and scanning the whole table.
  • Writing BETWEEN '2026-11-19' AND '2026-11-19 23:59:59' and missing rows in the last second's fractions.
  • Creating an expression index on LOWER(email) but querying with a different expression, like email ILIKE ?.

Likely interviewer follow-ups

  • Rewrite WHERE YEAR(order_date) = 2025 so it can use an index.
  • Why can LIKE 'abc%' use an index but LIKE '%abc' can't?
  • When would you create an expression index instead of rewriting the query?
Interview tip: Explain it as "the index stores the column's values, not the function's results", then show one rewrite. That one sentence makes the whole concept click for the interviewer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply SARGable Queries (Writing Index-Friendly WHERE Clauses) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Table Statistics, Cardinality Estimation & ANALYZE / VACUUM
Next topic
Common Anti-Patterns That Break Indexes (Functions on Columns, Implicit Casts, Leading %)