How Indexes Work & The Read vs Write Trade-off
See why indexes speed reads but add write and storage overhead.
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
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 INDEX idx_users_email ON users (email);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
EXPLAINSELECT *FROM usersWHERE email = 'a@b.com';PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative create and plan
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.
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.
SELECT indexrelname, idx_scanFROM pg_stat_user_indexesWHERE idx_scan = 0;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative unused-index report2 sample rows
| indexrelname | idx_scan |
|---|---|
| orders_legacy_status_idx | 0 |
| users_middle_name_idx | 0 |
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.
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.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
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.
WHERE email = ? ·ORDER BY created_atWhen 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
Strengths: No write overhead, no extra storage.
Watch out: Every lookup reads the whole table.
Strengths: Lookups in a few page reads; also serves ranges and ORDER BY.
Watch out: Each one slows writes and uses disk and memory.
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)?
Knowledge check
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.