Remember school notes?
Remember taking notes in school? You had pages of math, science, English and social studies. To find one detail later, you had to flip through page after page.
A book solves this with an index at the back. You look up the topic, see the page number, and go straight there.
A database index is the same idea. Let's see why a database needs one.
A database has the same job
A database has the same job, just on a much bigger scale. Say your app shows a user's feed and asks for one person's recent posts:
SELECT id, created_at, likes
FROM posts
WHERE user_id = 123
ORDER BY created_at DESC;
The posts table might have millions of rows. How does the database find user 123's posts without checking every single row?
Where the data lives: disk, pages and RAM
The database keeps its data on a disk, an SSD or a hard drive. It doesn't read the data row by row. It reads it in small blocks called pages.
To work with a page, the database copies it into memory, into an area called the buffer pool:
- If the page is already in the buffer pool, that's a hit, and it uses the copy.
- If not, that's a miss, and it reads the page from disk.
A page can hold table data or index data. The buffer pool keeps useful pages around and makes room for others when it fills up. A query does not load the whole table into memory, only the pages it needs.
Without an index: check rows one by one
Without a useful index, the database has to scan the table's pages and check rows one by one. This is called a sequential scan.
In many databases (PostgreSQL, for example), a table is stored as a heap: the rows sit in whatever order they arrived, not sorted by user_id. So user 123's posts can be anywhere, and the only way to be sure you found them all is to check everything.
A million rows means a million checks.
The B-tree: the index most databases use
An index works like the index in a book. The most common kind is the B-tree.
A B-tree keeps keys sorted and organizes them into a balanced tree. To find 123:
- Start at the top: 123 is between 100 and 200.
- Go down: it's between 120 and 150.
- One more step, and there it is.
Three steps, not a million rows. Real trees have more keys in each box, but they stay only a few levels deep even for huge tables.
Because the keys are sorted, ranges are easy too: "everything from 110 to 150", "posts after 1 January", or "prices between $10 and $20".
But an index isn't free:
- It uses disk space.
- Inserts, deletes, and updates to indexed columns have to update the index too, so writes get slower.
- If no query uses an index, drop it.
LSM trees: built for lots of writes
B-trees aren't the only approach. Some databases are built for very heavy write loads, like events, metrics or logs. They use an LSM tree (log-structured merge tree).
Here's how a write works:
- The new value goes into a sorted table in memory called the memtable.
- It's also added to a write-ahead log (WAL) on disk. If the server crashes, the database replays the WAL, so nothing is lost.
- When the memtable fills up, it's saved to disk as a sorted file called an SSTable. SSTables are never edited after they're written.
- In the background, compaction merges SSTables and clears out old versions and deleted data.
This turns many small writes into a few big disk writes, which is why LSM trees handle heavy writes so well.
Reading from an LSM tree: Bloom filters
Reads take a little more work, because the data is spread across memory and several files. The database checks the memtable first, then the files, newest first.
To avoid opening every file, SSTables usually come with a Bloom filter. It can answer in only two ways:
- "Definitely not here": skip this file.
- "Maybe": look inside the file.
Sorted files and their own small indexes then narrow down which part of the file to read.
Other searches need other indexes
Location. Imagine "find places near me". An index on latitude alone matches a band of places at that latitude around the whole world. You also need longitude, and then the real distance. A geohash (location turned into a sortable string) or an R-tree (boxes around shapes and regions) narrows the search to nearby areas first. Databases do this differently, so check your database's docs.
Text. For full-text search, an inverted index flips things around. Instead of "which words are in this document?", it answers "which documents contain this word?". Take these three documents:
- "B-trees are fast and reliable"
- "Hash tables are fast but limited"
- "B-trees handle range queries well"
The inverted index maps "B-trees" to documents 1 and 3, and "fast" to documents 1 and 2. That's the basic idea behind many search engines.
Composite and covering indexes
Back to the feed query. It filters by user_id and sorts by created_at. A composite index on both columns fits it:
CREATE INDEX idx_posts_user_created
ON posts (user_id, created_at);
The index keeps entries grouped by user, then sorted by time inside each user. So the database finds user 123's posts already in time order.
Order matters. The index is sorted by user_id first. It's great for queries that start with user_id, but it won't help much with a query that filters only on created_at.
The query also reads likes. If the index includes every column the query needs, it's a covering index. The database can answer straight from the index, with no trip to the table. In PostgreSQL:
CREATE INDEX idx_posts_user_created_cover
ON posts (user_id, created_at) INCLUDE (likes);
The cost: a bigger index and more work on every write. Use it for frequent queries, after checking how the database actually runs them.
Which index should you pick?
Start from the questions your app asks the database:
- Searching words? An inverted index.
- Places nearby? A geo index.
- Exact matches only? A hash index (no ranges).
- Most other queries, including ranges and sorting? A B-tree.
- Lots of writes? A database built on LSM storage.
- Several columns used together? A composite index.
- Reading just a few columns, very often? A covering index.
- Tiny table? A full scan can be perfectly fine.
Takeaway
Pick the index that fits your queries. Then check the query plan, and measure:
EXPLAIN ANALYZE
SELECT id, created_at, likes
FROM posts
WHERE user_id = 123
ORDER BY created_at DESC;
The plan shows whether the database actually uses your index or still scans the whole table.
I drew this as an animated whiteboard explainer. If it helped, I'd love to hear which index type you'd like me to go deeper on next, want to shout out to hellointerview site for the explaination i wrote it from what i learnt from there.











Top comments (0)