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 126/ 160
07. Indexing, Query Optimization & Performance Tuning

Partial Indexes (Filtered Indexes) & Expression / Functional Indexes

Index a subset of rows or an expression like LOWER(email) for hot paths.

AdvancedPartial Index · Expression Index3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A partial index only covers the rows you search often. An expression index covers a calculated value, like an email in lowercase.

Think of it like…

A library keeping a separate small catalogue just for books currently on loan (partial index), and another catalogue sorted by surname in lowercase so capitalisation never matters (expression index).

Where you’ve seen it

A jobs table with 50 million rows, of which 2,000 are pending: CREATE INDEX jobs_pending_idx ON jobs (created_at) WHERE status = 'pending'; is a few hundred kilobytes instead of gigabytes, and the worker query WHERE status = 'pending' ORDER BY created_at LIMIT 10 uses it instantly.

Words you’ll hear

Partial index
An index built only over rows that satisfy its WHERE clause.
Expression index
An index on a computed expression such as LOWER(email) or (data ->> 'sku').
Predicate implication
A query can use a partial index only if its WHERE implies the index's condition.
Partial unique index
Uniqueness enforced only among matching rows, such as active ones.

Visual diagram

Loading interactive diagram

Theory & example queries

Partial indexes

When queries always target a small, well-defined subset of rows (pending jobs, unread notifications, non-deleted records), index only that subset. The index is smaller, cheaper to maintain (rows outside the condition don't touch it) and more likely to stay in memory.

The planner uses it only when the query's WHERE clause implies the index condition, so WHERE status = 'pending' AND created_at < … qualifies but WHERE status = $1 with a parameter may not. A partial unique index enforces conditional rules: CREATE UNIQUE INDEX ON users (email) WHERE deleted_at IS NULL allows a deleted account's email to be reused while keeping active emails unique.

One active subscription per userQuery 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 UNIQUE INDEX one_active_sub ON subscriptions (user_id)2WHERE3  status = 'active';
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/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command response
CREATE INDEX

Note: PostgreSQL reports CREATE INDEX when the partial unique index is built successfully. It reports an error if two active subscriptions for one user already exist.

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

Key takeaway: Index the subset you query; use partial unique indexes for conditional rules.

Expression indexes

A normal index on email can't help WHERE LOWER(email) = 'asha@x.com', because the index stores the original values. An expression index on LOWER(email) stores exactly what the query compares, so it's used, as long as the query uses the identical expression. The same works for JSON fields ((attributes ->> 'sku')) and computed values like (created_at::date).

Expressions in indexes must be immutable: the same input always gives the same result. Functions that depend on the timezone or current time aren't allowed. Each expression index adds write cost, like any index, and the planner keeps separate statistics for it after ANALYZE. MySQL supports functional indexes from 8.0.13; SQL Server achieves the same with indexed computed columns.

Fast case-insensitive login lookupQuery 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 UNIQUE INDEX 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  id3FROM4  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
id
42

Note: The index creation must first succeed without duplicate lowercased emails. The sample parameter matches one user; PostgreSQL returns no rows if the email is absent.

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

then

Key takeaway: Index the exact expression your queries use.

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 1Workload

Find the hot query's shape

Note the exact WHERE clause of the frequent query: a fixed status filter, or a function applied to a column.

SQL at this stepReadable preview
1WHERE status = 'pending' ·2WHERE LOWER(email) = ?
What to watch at this step
Source
pg_stat_statements
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A partial index (SQL Server calls it a filtered index) indexes only the rows that match a WHERE condition: CREATE INDEX ON orders (created_at) WHERE status = 'pending'. An expression index indexes the result of an expression instead of a raw column: CREATE INDEX ON users (LOWER(email)). Both make specific, hot queries fast with a much smaller or more precise index.

Why it matters: Most queries on a queue table only care about the few pending rows; most lookups on emails are case-insensitive. A full index on everything wastes space and write time, and a plain column index can't help a query on LOWER(email). These two index types solve exactly those problems, and partial unique indexes enforce rules like "one active subscription per user".

When to reach for it

  • Queue and job tables (pending rows)
  • Soft-deleted tables (WHERE deleted_at IS NULL)
  • Case-insensitive lookups and JSON field filters

When to avoid or be careful

  • Partial indexes whose condition the queries don't repeat
  • Expression indexes on functions the queries don't use identically
  • Partial indexes on conditions that match most of the table

Full index vs partial index vs expression index

Full column index
Best for: General lookups across all rows

Strengths: Used by many different queries.

Watch out: Large; every write maintains it; useless for functions on the column.

Partial index
Best for: Queries that always target a small subset (pending, active, not deleted)

Strengths: Tiny, cheap to maintain; enables conditional uniqueness.

Watch out: Only used when the query's WHERE implies its condition.

Expression index
Best for: Queries on LOWER(), JSON fields or other computed values

Strengths: Makes non-SARGable expressions searchable.

Watch out: Only matches the identical expression; immutable functions only.

Interview signals & numbers to know

When this topic comes up

  • “The queue table is huge but we only query pending jobs”
  • “Case-insensitive email lookup is slow”
  • “Email must be unique among active users”
  • Soft deletes
  • Index bloat

Benchmarks & rules of thumb

MySQL 8.0.13 -
functional indexes added
0 -
partial indexes in MySQL
Immutable -
required for index expressions

Common mistakes & follow-ups

Common interview mistakes

  • Creating an index on LOWER(email) but querying WHERE email ILIKE $1, which can't use it.
  • Creating a partial index WHERE status = 'pending' and querying with a parameterised status the planner can't prove matches.
  • Making email UNIQUE on a soft-delete table, so deleted accounts block re-registration.

Likely interviewer follow-ups

  • How would you enforce a unique email only among non-deleted users?
  • Why isn't my index on email used by WHERE LOWER(email) = …?
  • When would a partial index be better than a full one?
Interview tip: Give the queue-table example for partial indexes and the LOWER(email) example for expression indexes, then mention the partial unique index trick. Three practical uses in one answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Partial Indexes (Filtered Indexes) & Expression / Functional Indexes with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Covering Indexes (INCLUDE Clause) & Index-Only Scans
Next topic
Specialized Indexes (Hash, GIN, GiST, BRIN for Time-Series)