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

How Indexes Work & The Read vs Write Trade-off

See why indexes speed reads but add write and storage overhead.

BeginnerIndex Lookup · Write Amplification3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

An index is a sorted list of values with pointers to their rows, so the database can jump straight to what you're looking for.

Think of it like…

The index at the back of a textbook: to find "normalization" you look it up alphabetically and jump to page 214 instead of reading the whole book. And every time the book changes, the index has to be updated too.

Where you’ve seen it

SELECT * FROM users WHERE email = 'a@b.com' on 20 million users: without an index, a sequential scan reads the whole table, which takes seconds. With a B-tree index on email it's about four page reads, well under a millisecond.

Words you’ll hear

B-tree
A balanced, sorted tree and the default index type. Good for =, <, >, BETWEEN and ORDER BY.
Selectivity
The fraction of rows a condition matches. Indexes help most when it's small.
Write overhead
Every INSERT and DELETE, and every UPDATE of an indexed column, must also update each index.
Index-only scan
Answering a query from the index alone, without visiting the table.

Visual diagram

Loading interactive diagram

Theory & example queries

How a B-tree lookup works

A B-tree keeps keys sorted in fixed-size pages. The root points to child pages covering key ranges, down to leaf pages that hold each key and a pointer to its row. Each page holds hundreds of keys, so the tree stays shallow: 3–4 levels cover hundreds of millions of rows.

Because the keys are sorted, the same index serves equality, ranges (<, >, BETWEEN), prefix LIKE ('abc%') and ORDER BY on that column. It can't help with a leading wildcard ('%abc'), or with a function applied to the column unless you create an expression index.

Create it, then verify itQuery 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 ON users (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
1EXPLAIN2SELECT3  *4FROM5  users6WHERE7  email = 'a@b.com';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative create and plan
CREATE INDEX Index Scan using idx_users_email on users Index Cond: (email = 'a@b.com')

Note: The planner may use a bitmap, index-only scan or sequential scan depending on statistics, table size and selectivity; the index itself must already exist successfully.

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

then

should show an Index Scan instead of a Seq Scan.

Key takeaway: Sorted and shallow means a few page reads instead of a full scan.

The read vs write trade-off

Every index has to be updated on each INSERT and DELETE, and on UPDATEs that change indexed columns. A table with 10 indexes does roughly 10 extra writes per insert, uses more disk and memory, and loads in bulk more slowly.

The planner also skips an index when it wouldn't help. If a condition matches a large share of the table (say status = 'active' for 80% of rows), reading the table sequentially is cheaper than jumping back and forth through the index.

Finding unused indexes (PostgreSQL)Query 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
1SELECT2  indexrelname,3  idx_scan4FROM5  pg_stat_user_indexes6WHERE7  idx_scan = 0;
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/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative unused-index report2 sample rows
Representative unused-index report
indexrelnameidx_scan
orders_legacy_status_idx0
users_middle_name_idx0

Note: pg_stat_user_indexes counters are resettable and reflect the current statistics snapshot; a zero does not by itself prove an index is safe to drop.

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

lists indexes that have never been scanned. They only cost you writes.

Key takeaway: Index what you often filter, join and sort on, and nothing else.

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

Start from a real slow query

Index for queries you actually run (from pg_stat_statements or the slow query log), not for every column. Note the WHERE, JOIN and ORDER BY columns.

SQL at this stepReadable preview
1WHERE email = ? ·2ORDER BY created_at
What to watch at this step
Source
slow query log
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

An index is a separate, sorted data structure (usually a B-tree) that maps column values to the rows containing them. Instead of reading every row, the database walks the tree to the matching values in a handful of page reads.

Why it matters: Indexes are the biggest single lever for query speed: a lookup that scans 50 million rows can drop to a few milliseconds. But every index slows down writes and takes space, so knowing when *not* to add one matters just as much.

When to reach for it

  • Columns used often in WHERE, JOIN ON and ORDER BY
  • Foreign key columns: PostgreSQL doesn't index them automatically
  • Uniqueness rules: a UNIQUE constraint creates its index for you

When to avoid or be careful

  • Low-selectivity columns like boolean flags (a partial index on the rare value is better)
  • Write-heavy tables where the index is rarely read
  • Duplicate indexes, such as (a) when (a, b) already exists

No index vs targeted indexes vs indexing everything

No index (Seq Scan)
Best for: Small tables, or queries that return a large share of rows

Strengths: No write overhead, no extra storage.

Watch out: Every lookup reads the whole table.

Targeted B-tree indexes
Best for: Frequent filters, joins and sorts on selective columns

Strengths: Lookups in a few page reads; also serves ranges and ORDER BY.

Watch out: Each one slows writes and uses disk and memory.

An index on every column
Best for: Nothing: it's an anti-pattern

Strengths: Any single-column filter might be fast.

Watch out: Slow writes and bloated storage, and separate single-column indexes rarely beat one well-chosen composite index.

Interview signals & numbers to know

When this topic comes up

  • “How would you speed up this query?”
  • “Why not index every column?”
  • Seq Scan on a big table
  • Inserts got slower after adding indexes
  • B-tree

Benchmarks & rules of thumb

3–4 -
B-tree levels for hundreds of millions of rows
8 KB -
default PostgreSQL page size
+1 write -
per index, on every insert

Common mistakes & follow-ups

Common interview mistakes

  • Indexing every column "just in case" and slowing down every write.
  • Expecting an index to be used when the condition matches most of the table.
  • Forgetting that PostgreSQL doesn't index foreign key columns automatically, which makes joins and cascading deletes slow.

Likely interviewer follow-ups

  • Why might the database ignore an index you created?
  • What does an index cost on a write-heavy table?
  • How is a composite index on (a, b) different from two separate indexes on (a) and (b)?
Interview tip: Explain the lookup (sorted tree, a few page reads), then immediately give the cost (writes, storage) and when the planner skips it. Interviewers want the trade-off, not just "indexes make things fast".

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply How Indexes Work & The Read vs Write Trade-off with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
How Databases Store Data on Disk (Pages, Blocks, Heap, B-Trees)
Next topic
B-Tree Indexes (Single-Column vs Composite / Multi-Column Indexes)