SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Indexing

A shortcut so the database does not read every row to find the one you want.

⏱ 15 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An index is a separate, sorted structure that lets the database find rows without reading the whole table. It works like the index at the back of a book.

  • Without an index the database does a full table scan: it reads every row. Cost grows with table size.
  • With a B-tree index it needs only a few steps, even for hundreds of millions of rows.
  • The price: indexes take disk space and make every insert, update and delete slower.
  • Good indexing means the right columns, in the right order, and not too many.

02Concept: What is it?

A table is stored in the order rows were added. To find "orders for customer 42", the database would have to look at every row. An index keeps a small, sorted copy of one or more columns, each entry pointing to the row. Because it is sorted, the database can jump to the right place, like a binary search, instead of reading everything.

Most relational databases use a B-tree (usually the B+ tree variant) as the default index. It is a shallow, wide tree: each page holds hundreds of keys, so even a table with a billion rows needs only about 4 or 5 page reads to reach one row.

Scan vs index lookup
Full table scan
Rows readevery row
Timegrows with the table
Index lookup
Rows reada few pages
Timealmost flat
The index finds the row in a few steps. The scan walks the whole table.
🧠An index is a trade
You pay on writes (every index must be updated) and on space, and you gain on reads. Index what you search, not everything.

03Real-Life Example

🍡The Book Index and the Library
You want every page that mentions "monsoon" in a 900-page book. Without help you read all 900 pages. The index at the back lists "monsoon: pages 14, 203, 540", in alphabetical order, so you find it in seconds. But the printer had to build and update that index, and the book got a few pages thicker. If the book is edited often, keeping the index right takes work.
Book
Database
Reading every page
Full table scan
The index at the back
A B-tree index on a column
Entries sorted alphabetically
Keys kept in sorted order
Page numbers next to each entry
Row pointers (or the row itself)
Index by author, then by title
Composite index on (author, title)
Looking for a title only in an author-first index
Cannot use the left-most-column rule
Updating the index after every edit
Extra cost on every write
Looking up key 42 in a B-tree
🌳Root page1 to 1M: go to child 1
→↓1
🌿Inner page40 to 80: go to child 3
→↓2
πŸƒLeaf pagekey 42 found
→↓3
πŸ“„Table row

04Why Do We Need It?

⚑Fast reads
Lookups, ranges and sorting drop from reading everything to a few page reads.
πŸ“ˆScales with data
Tree depth grows very slowly, so 10 times more rows adds almost no time.
↕️Free sorting
ORDER BY on an indexed column can read in order and skip a sort.
πŸ›‘οΈUniqueness
A unique index stops two rows having the same email.
πŸ”—Faster joins
Join keys with an index avoid scanning the other table for every row.
πŸ”’Less locking
Touching fewer rows means fewer locks and less contention.
Do not make the database search. Make it jump.

05Where Do We Use It?

πŸ”‘Primary keys
Every table has one, and databases build an index for it.
πŸ”—Foreign keys and join columns
customer_id on orders, so joins and deletes are quick.
πŸ”WHERE filters
Columns you filter on often: email, status, created_at.
↕️ORDER BY and range queries
Latest 20 orders, prices between 10 and 50.
🧾Unique rules
Email, username, order number.
πŸ”€Text and special data
Full-text, JSON, geo and vector indexes for other kinds of questions.

06Types / Parts / How It Works

Kinds of index

KindWhat it isGood for
B-tree (B+ tree)A sorted, balanced tree. The default.Equals, ranges, sorting, prefix match
Hash indexA hash table from key to row.Equals only. Not ranges or sorting.
Composite (multi-column)One index over several columns in a fixed order.Queries that filter on those columns together
Unique indexAn index that also rejects duplicates.Email, username, natural keys
Covering indexHolds every column the query needs, so the table is never read.Hot queries that read few columns
Partial (filtered) indexIndexes only rows that match a condition.WHERE status = 'ACTIVE' when most rows are old
Clustered indexThe table itself is stored in index order (one per table).Range scans on the primary key
Inverted, GIN, geo, vectorSpecialised structures for words, arrays, JSON, maps, embeddings.Search, tags, location, similarity

The left-most prefix rule

A composite index on (country, status, day) is sorted by country first, then status inside a country, then day. It helps queries that start from the left: country; country + status; country + status + day. It does not help a query on status alone, because statuses are scattered across all countries. A range on one column (day between...) ends how far into the index the search can narrow, so put equality columns first and the range column last.

Composite index example (PostgreSQL / MySQL style)
CREATE INDEX idx_orders_country_status_day
  ON orders (country, status, day);

-- uses the index (left-most prefix):
SELECT * FROM orders WHERE country = 'IN' AND status = 'PAID';

-- cannot use it well (skips the first column):
SELECT * FROM orders WHERE status = 'PAID';

-- see what the database chose:
EXPLAIN SELECT * FROM orders WHERE country = 'IN';
Add an index
Read side wins
  • Lookups, ranges, sorts are fast
  • Joins and uniqueness checks are quick
  • Takes extra disk space
  • Every write has more to do
Do not index
Write side wins
  • Writes are cheapest
  • No extra space
  • Every read is a scan
  • Fine for tiny or write-only tables
Covering index: the table is never touched
❓SELECT email, status WHERE email = ?
→↓index on (email, status)
βœ…Answer from the indexno table read
Query Index only
If the index already contains the columns in the SELECT, the database answers from the index alone.
VisualizerScan vs index, column order, and the cost of more indexesRaise the rows to 1 billion. Then change the query and the column order. Last, push the index count to 10 and watch writes.

1. Table scan vs index lookup

Table scan
1.0M row reads
B-tree index
4 reads (3 levels + the row)
Bars use a log scale, so you can see both. Real scan cost grows in a straight line; index cost barely moves.
Scan
1.0M
rows read
Index
4
tree height 3
Less work
250.0kx
At 1.0M rows a scan reads about 1.0M rows. The B-tree needs 3 page steps and 1 row fetch (4 reads). That is roughly 250.0k times less work.

2. Composite index: column order matters (10M row orders table)

Query

WHERE country = 'IN' AND status = 'PAID'

Index on (a, b, c)
1. country (narrows the search)2. status (narrows the search)3. day (not used)
No index
10.0M rows
This index
40.0k entries read
Result
40.0k rows returned
Entries read
40.0k
Rows returned
40.0k
Wasted reads
1.0x
read / returned
Prefix used: country, status. It reads 40.0k entries for 40.0k result rows. Good match between index order and query.

3. Every extra index slows writes

Cost of one write
5.5x
table + 3 indexes
Total work vs no index
1%
lower is better
Disk used
2.0x
table + indexes
Each insert updates the table and 3 indexes (about 5.5x a bare write). Reads got far cheaper, so the total is lower than with no index.

Simplified models with fixed maths (no random numbers). The tree uses 200 keys per page. In section 2 we assume equal spread of values: 50 countries, 5 statuses, 365 days. Real planners use statistics and may choose differently. Part 3 uses made-up relative costs to show the shape of the trade-off, not real numbers.

07How to Use It / Steps / Implementation

Choosing indexes

  1. 1
    Find the slow or common queries
    Use the slow query log or a query monitor. Do not guess.
  2. 2
    Read the plan with EXPLAIN
    See if the database does a sequential scan or an index scan, and how many rows it expects.
  3. 3
    Index the columns in WHERE, JOIN and ORDER BY
    Start with columns that are selective, meaning they narrow the result a lot.
  4. 4
    Order composite columns well
    Equality columns first, then the range or sort column. Match the queries you actually run.
  5. 5
    Consider a covering or partial index
    For a hot query, include the needed columns. For a rare status, index just those rows.
  6. 6
    Remove unused and duplicate indexes
    An index on (a) is usually redundant if you have (a, b). Check usage statistics.
  7. 7
    Re-check after changes
    Data grows and queries change. Look again at plans and index use regularly.
⚠️Low-selectivity columns
An index on a column with very few distinct values (like a boolean or a status with 3 values) rarely helps by itself, because it matches a big share of the table. Use it as part of a composite or partial index instead.
Where the cost sitsreads get cheaper, each write gets more expensive

08Key Terms to Know

TermMeaning in easy words
IndexA sorted structure that helps find rows fast
Full table scanReading every row of a table
B-tree / B+ treeA balanced, wide tree used by most indexes
SelectivityHow much a filter narrows the result. Higher selectivity means fewer rows match
Composite indexAn index on several columns, in order
Left-most prefixA composite index helps only queries that use its first columns
Covering indexAn index that holds all columns a query needs
Clustered indexThe index that decides how the table rows are stored
CardinalityThe number of distinct values in a column
EXPLAINA command that shows how the database will run a query

09Pros, Cons and Trade-offs

βœ… Pros
  • Reads, joins and sorts become much faster
  • Scales well as data grows
  • Enforces uniqueness
  • Supports covering reads
  • Reduces locks and load
⚠️ Cons
  • Slower inserts, updates and deletes
  • Uses extra disk and memory
  • Wrong index order may never be used
  • Too many indexes are a maintenance burden
  • Statistics can go stale and mislead the planner

Trade-offs

ChoiceWe gainWe lose
More indexesMore query shapes are fastSlower writes, more space
Fewer indexesFast writes, less spaceSlow reads for the missing paths
Wide composite indexCovers many queries, may avoid table readsLarge and costly on every write
Covering indexNo table lookup at allBigger index to store and update
Partial indexSmall and cheapOnly helps queries with the same condition

10Common Problems and Mistakes

Common mistakes

  1. Index everything. Writes slow down and most indexes are never used.
  2. Wrong column order. An index on (b, a) does not help a query that filters only on a.
  3. Functions on the column. WHERE lower(email) = ... cannot use a plain index on email. Use an expression index.
  4. Leading wildcard. LIKE '%shop' cannot use a normal B-tree index.
  5. Type mismatch. Comparing a text column with a number can force a scan.
  6. Never reading EXPLAIN. You cannot tell what the database really does.

Things to watch

πŸ“ŠStale statistics
The planner picks plans from table stats. Refresh them after big data changes.
🧹Index bloat
Heavy updates and deletes leave gaps. Rebuild when needed.
⏳Building on a big live table
Use the online or concurrent options so you do not block writes.
🎲Random keys
Random ids (like some UUIDs) scatter inserts across the tree and cause more page splits.

11Real-World Examples

🐘PostgreSQL
B-tree by default, plus GIN, GiST, BRIN and hash. EXPLAIN ANALYZE shows plans.
🐬MySQL / InnoDB
The primary key is a clustered index, and secondary indexes point to the primary key.
πŸƒMongoDB
B-tree indexes on fields, including compound and TTL indexes.
πŸ”Elasticsearch
Inverted indexes make text search fast (general idea).
βš™οΈWide-column and key-value stores
Data is keyed by design, and secondary indexes are used carefully because they cost more.
πŸ›’Online shops
Orders by customer and date, products by category and price: classic composite indexes.
πŸ“Note
These are general ideas. Index types and options differ by database and version.
Mini case: a slow orders page
🐒Beforescan 10M rows
→↓EXPLAIN shows Seq Scan
πŸ› οΈAdd index(customer_id, created_at)
→↓re-run
πŸš€Afterreads 20 rows
One well chosen composite index turns a seconds-long scan into a few milliseconds.

12Related Topics to Read Next

B-Trees and B+ Trees→

The structure behind most indexes.

LSM Trees→

The write-friendly alternative to B-trees.

Query Optimization→

Indexes are the first tool for faster queries.

Relational Databases→

Where indexes, plans and joins live.

Partitioning→

Another way to read less data for each query.

Full-Text Search Engines→

Inverted indexes for searching words.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a sorted structure that lets the database jump to rows instead of scanning.
  • βœ”Default: B-tree. A few page reads even for billions of rows.
  • βœ”Composite: left-most prefix. Equality columns first, range last.
  • βœ”Boost: covering index (no table read), partial index (fewer rows).
  • βœ”Cost: disk space and slower writes for every index.
  • βœ”Breaks it: functions on columns, leading wildcards, wrong order, type mismatch.
  • βœ”Tool: EXPLAIN. Measure, do not guess.
  • βœ”One line: β€œIndex what you search, keep it lean, and check the plan.”
← Previous
In-Memory Databases
Next β†’
Partitioning