Database Indexing
Trade some write speed and storage for dramatically faster reads — and know when the trade stops paying off.
Indexing in 30 seconds
- An index is a sorted lookup structure that turns a full-table scan into a quick jump to matching rows.
- The trade: faster reads in exchange for slower writes and extra storage — every write updates every index.
- B-tree: sorted, updated in place — great for read-heavy relational workloads and range scans.
- LSM tree: buffers writes and compacts later — great for write-heavy and time-series workloads.
- Composite index order matters; a covering index answers a query from the index alone.
- Don't over-index: index the columns real queries filter and sort on, and drop ones the planner never uses.
The index at the back of a book
Say you want every mention of 'photosynthesis' in a 900-page textbook. You could start at page one and read every page — guaranteed to work, and painfully slow. Or you flip to the index at the back, find 'photosynthesis → 212, 455, 603,' and jump straight to those three pages. The index is a second, smaller, sorted list that exists only to help you find things fast. A database index is exactly that: a separate sorted structure whose only job is to turn 'read everything' into 'jump straight there.'
And notice the hidden cost, because it's the whole story of indexing: the book's index had to be built, and if a new edition adds a paragraph about photosynthesis on page 50, the index has to be updated too. Faster to look things up, more work to keep current. That bargain — quicker reads, slower writes — is the single idea this page keeps returning to.
The problem it solves
Without an index, finding rows that match a condition means scanning every row — fine for a thousand records, catastrophic for a billion. An index is a separate, sorted data structure that lets the database jump straight to the matching rows, turning a full-table scan into a quick lookup. The cost: indexes take storage and must be updated on every write, so they speed up reads at the expense of writes.
-- No index: the DB must read EVERY row to check the condition.
SELECT * FROM users WHERE email = 'ada@x.com';
-- plan: Seq Scan on users (cost grows with every row -> O(n))
CREATE INDEX idx_users_email ON users (email);
-- With the index: jump straight to matching rows via the sorted tree.
SELECT * FROM users WHERE email = 'ada@x.com';
-- plan: Index Scan using idx_users_email (~O(log n))The core idea, plainly
An index is like the index at the back of a book — instead of reading every page to find a topic, you look it up and jump to the right page. The database keeps this lookup structure in sync as data changes. The art is indexing the columns you actually filter and sort on, and not indexing everything, because each extra index slows every insert and update.
Why 'sorted' is the magic word
Everything an index does flows from one property: it keeps the indexed column in sorted order, separate from the table. Sorted order is what makes the binary-search 'halve it each time' jump possible, and it's also what makes range queries cheap — 'all orders between March and June' is just a contiguous slice of a sorted structure, read in one sweep. A pile of unsorted rows can't do either; it can only be scanned end to end.
# The index stores (value -> row location), kept sorted by value:
# aa@x.com -> row 5120
# ab@x.com -> row 99
# ...
# ada@x.com -> row 42 <- binary search lands here in ~log2(n) hops
# ...
# zz@x.com -> row 7
#
# Looking up 'ada@x.com' in a BILLION rows takes ~30 comparisons,
# because each comparison throws away half of what's left.The two dominant structures
| Structure | How it works | Great at | Weak at | Used by |
|---|---|---|---|---|
| B-tree | Balanced sorted tree, updated in place. | Fast reads and range scans; predictable. | Random writes cause in-place updates. | Most relational DBs (Postgres, MySQL). |
| LSM tree | Buffer writes in memory, flush to sorted files, compact later. | Very high write throughput. | Reads may check several files; compaction overhead. | Write-heavy stores (Cassandra, RocksDB). |
The split is about which operation you optimize. B-trees keep data sorted on disk and update it in place, which makes reads and range queries fast — ideal for read-heavy relational workloads. LSM trees turn random writes into fast sequential appends and merge files in the background, which makes writes cheap — ideal for write-heavy and time-series workloads. Bloom filters (see below) often sit in front of LSM files to skip the ones that can't contain a key.
Why two structures and not one?
This is a 'gap' worth naming: no single structure wins at both reads and writes, so you get to pick which one you want to be cheap. A B-tree updates a value in place, which keeps reads fast but makes every write hunt down the right spot on disk and overwrite it — random I/O, which disks dislike. An LSM tree never updates in place; it just appends the new value to a log and sorts things out later during background compaction. That makes writes a cheap sequential append, but a read may have to check several files to find the latest version of a key.
Practical indexing concerns
- Composite indexes — an index on
(status, created_at)serves queries filtering on both, in that order. Column order matters. - Covering index — if an index contains all columns a query needs, the DB answers from the index alone, skipping the table.
- Write amplification — every index multiplies the work of each write; too many indexes make writes crawl.
- Low selectivity — indexing a column with few distinct values (like a boolean) rarely helps; the DB may scan anyway.
-- A composite index is sorted by the FIRST column, then the second.
CREATE INDEX idx_orders ON orders (status, created_at);
SELECT * FROM orders WHERE status = 'open'; -- uses index (leftmost)
SELECT * FROM orders WHERE status = 'open' ORDER BY created_at; -- uses index fully
SELECT * FROM orders WHERE created_at > '2026-01-01'; -- CANNOT use it:
-- the query skips the leading column, so the sort order doesn't help.The covering index — answering without touching the table
A covering index is a neat trick worth understanding because it's where indexing pays off most. Normally an index gives you a pointer to the row, then the database follows that pointer to the table to read the other columns you asked for. But if the index already contains every column the query needs, there's nothing to fetch from the table — the index alone is the answer. The query never touches the table at all.
-- Query needs only status and created_at, and both are in the index:
CREATE INDEX idx_orders ON orders (status, created_at);
SELECT status, created_at FROM orders WHERE status = 'open';
-- plan: Index Only Scan <- never reads the table, just the index
-- Add a third needed column and it's no longer covering:
SELECT status, created_at, total FROM orders WHERE status = 'open';
-- now the DB must visit the table for `total` -> extra lookups.The gap an index can't fill — when it makes things worse
An index isn't free, and in two situations it actively hurts. First, on a write-heavy table: every insert and update must also update every index, so a table with eight indexes does nine writes per logical write. Pile on indexes 'just in case' and your writes slow to a crawl — the index tax quietly becomes the bottleneck. Second, on a low-selectivity column: indexing a boolean like is_active barely narrows anything, since half the rows match, so the planner often ignores the index and scans anyway — you paid the write cost for nothing.
-- Every index on this table must be updated on EVERY write:
CREATE INDEX idx_a ON events (user_id);
CREATE INDEX idx_b ON events (type);
CREATE INDEX idx_c ON events (created_at);
CREATE INDEX idx_d ON events (session_id);
INSERT INTO events (...) VALUES (...);
-- 1 row written to the table
-- + 4 index entries maintained = 5x the write work.
-- On a write-heavy table, those extra writes become the bottleneck.Indexing is the clearest everyday example of a read-versus-write trade — it's where you decide, column by column, which operations you want to be fast and which you're willing to slow down.
Why it matters
- The difference between an indexed lookup and a full scan is the difference between milliseconds and minutes at scale.
- The storage engine choice (B-tree vs LSM) sets your write ceiling before you write a line of app code.
- Thoughtful indexing is often the cheapest 'scaling' there is — making the existing database do far less work.
If ignored
- Queries that were fine at a thousand rows crawl at a billion, and the app feels broken under growth.
- Over-indexing quietly makes every insert and update slower until writes become the new bottleneck.
- A wrong composite-column order or a low-selectivity index means the planner ignores it and scans anyway.
Where it fits
- Sits inside the storage engine, between a query and the raw data on disk.
- Shapes how every database family delivers its intended access pattern.
- Usually the first lever pulled when scaling a database, before caching or replicas.
Related topics
- Bloom filters: sit in front of LSM files to skip ones that can't hold a key
- Database scaling: indexing and tuning are step one of the scaling playbook
- Database types: each family leans on a storage engine tuned for its workload
- Latency vs throughput: the read-vs-write trade an index makes, named at the concept level
Interview lens
Questions it unlocks
- This query is slow — how do you speed it up?
- B-tree or LSM storage for this workload, and why?
- What's the downside of adding an index?
60-second answer
An index trades write speed and storage for fast reads by keeping a sorted lookup structure, so I index the columns real queries filter and sort on — often as composite or covering indexes — and avoid over-indexing because each one slows every write. For the storage engine, I pick B-tree for read-heavy relational workloads and range scans, and LSM for write-heavy or time-series workloads where turning random writes into sequential appends wins. For semantic search I'd add an approximate-nearest-neighbor vector index, accepting a little recall loss for speed.
Common traps
- Adding indexes for every slow query without counting the write cost.
- Getting composite-index column order wrong so the index isn't used.
- Indexing low-selectivity columns that don't actually help.