4.4.13Databases

Indexing — B-tree index, hash index, full-text

2,078 words9 min readdifficulty · medium1 backlinks

WHY indexes exist

The cost we trade for fast reads:

  • Extra storage (the index is a copy of the indexed column + a row pointer).
  • Slower writes: every INSERT/UPDATE/DELETE must also update each index.

That trade-off is the 80/20 of database tuning: index the columns you filter/join/sort on, do not index everything.


1. B-tree index (the default, ~90% of all indexes)

HOW the structure works

  • A node has up to mm children (mm = the branching factor, often hundreds because one node = one disk page of ~8 KB).
  • Internal nodes store separator keys that route the search ("keys < 30 go left").
  • Leaves store the actual key → row-pointer pairs in sorted order.

WHAT B-trees are great at

  • Equality: WHERE id = 42 → walk down, O(logN)O(\log N).
  • Range: WHERE age BETWEEN 20 AND 30 → find 20, then walk the linked leaf list — this is why leaves are sorted+linked.
  • Sorting / ORDER BY: data is already in order, no extra sort.
  • Prefix matching: LIKE 'app%' works; LIKE '%pp' does not (no known prefix to start at).
Figure — Indexing — B-tree index, hash index, full-text

2. Hash index

Operation B-tree Hash
= equality O(logN)O(\log N) O(1)O(1)
range / <, >, BETWEEN O(logN+k)O(\log N + k) ❌ full scan
ORDER BY ✅ free
LIKE 'pre%'

3. Full-text index


Common mistakes (steeled)


Recall Feynman: explain it to a 12-year-old

Imagine a giant book with a billion pages. Finding the word "dragon" by reading every page would take forever. So at the back we keep an index: words in ABC order with page numbers. A B-tree is that alphabetical index — sorted, so you can also grab every word from "cat" to "dog" easily. A hash index is like a magic coat-check: you give the exact ticket number and instantly get your item, but you can't ask for "all tickets between 10 and 20." A full-text index is a list saying "the word dragon appears on pages 4, 17, 88" — perfect for finding words inside sentences.


Flashcards

What data-structure property makes a B-tree lookup O(logmN)O(\log_m N) disk reads?
It's balanced (all leaves same depth) and each node = one disk page with high branching factor mm, so h=logmNh=\lceil\log_m N\rceil.
Why are B+tree leaf nodes linked in a sorted list?
To support fast range scans / ORDER BY — find the start, then walk the leaves sequentially.
Why does a hash index fail for ORDER BY and range queries?
Hashing scatters keys to destroy order, so adjacent values land in unrelated buckets; no order to walk.
For ~1 billion rows with branching factor 100, how many levels does the B-tree have?
~5, since log100109=4.5\log_{100}10^9 = 4.5.
Why can't a normal B-tree index serve LIKE '%word%'?
A leading wildcard gives no known prefix to start the descent, forcing a full scan; use a full-text/inverted index.
What is an inverted index?
A map from each word/token → list of documents (postings) containing it, used for full-text search.
What three text preprocessing steps build a full-text index?
Tokenization, stemming, stop-word removal.
State the leftmost-prefix rule for composite B-tree indexes.
An index on (a,b) helps queries on a or (a,b) but not b alone, because it's sorted by a first.
What is the main cost/trade-off of adding an index?
Extra storage + slower writes (every insert/update/delete must maintain the index).
When is a hash index the right choice over B-tree?
When queries are pure equality lookups with no ranges/sorting (e.g., session_id cache).

Connections

  • Query Optimization — the planner decides whether to use an index via cost estimates.
  • B+ Tree Data Structure — the underlying balanced tree.
  • Hashing — hash functions, collisions, load factor behind hash indexes.
  • Disk vs Memory I/O — why we count page reads, not comparisons.
  • Clustered vs Non-clustered Index — where the actual row lives.
  • Big-O NotationO(logN)O(\log N) vs O(1)O(1) vs O(N)O(N).

Concept Map

motivates

avoided by

main type

type

type

traded for

stores data in

lookup cost

enables

gives

only supports

supports

Full table scan O of N

Index: sorted or hashed structure

Disk I/O bottleneck

B-tree / B+tree index

Hash index

Full-text index

Sorted linked leaves

Height h = log base m of N

Range and ORDER BY queries

Equality lookup

Extra storage + slower writes

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Socho tumhare paas ek table hai jisme 1 crore rows hain. Agar tum WHERE email = 'x' chalao bina index ke, to database ko poori table scan karni padti hai — har row padho aur compare karo. Yeh slow hai kyunki asli bottleneck disk I/O hai, CPU nahi. Index ek alag sorted ya hashed structure hai jo seedha row tak le jaata hai, bilkul kitaab ke peeche wale index ki tarah.

B-tree sabse common index hai (~90% cases). Yeh ek balanced tree hai jahan har node ek disk page jitna bada hota hai, isliye branching factor bahut high hota hai (sau-sau children). Iska matlab tree bahut chhota aur chaurra hota hai — 1 billion rows sirf ~5 levels mein, yaani ~5 disk reads. Aur kyunki leaves sorted aur linked hote hain, range queries (BETWEEN) aur ORDER BY bhi free mein ho jaate hain.

Hash index key ko hash karke seedha bucket mein daal deta hai — exact match ke liye O(1), sabse fast. Lekin hashing order ko jaan-bhoojh kar tod deti hai, isliye >, <, ya ORDER BY ke liye yeh bekaar hai. Sirf tab use karo jab queries pure equality hon (jaise session_id).

Full-text index tab kaam aata hai jab tumhe text ke andar word dhoondhna ho. LIKE '%word%' B-tree use nahi kar sakta. Iske liye inverted index banta hai: har word ke saamne uss word wale documents ki list. Query sat AND dog = sets ka intersection. Yaad rakho: B for Between, H for Hit-exact, F for Find-words — yahi 80/20 hai indexing ka.

Go deeper — visual, from zero

Test yourself — Databases

Connections