What an index actually is
Without an index, WHERE email = 'a@b.com' scans every row: 100M rows, 100M comparisons, seconds to minutes. An index is an auxiliary sorted data structure, usually a B-Tree, mapping the indexed column's values to row locations. Lookup cost drops from O(n) to O(log n): for 100M rows, about 27 comparisons, milliseconds. The trade: extra disk, and every write now also updates every index.
B-Tree intuition (and why it beats a hash for most things)
A phone directory: names sorted, so finding "Sharma" takes a few page-splits, not a full read. A B-Tree generalizes this for disk: fat nodes (hundreds of keys each) so the tree is only 3-4 levels deep even for billions of rows, and each level is one disk page read. Because it is sorted, it also answers range queries (BETWEEN, >, ORDER BY, prefix LIKE 'abc%'), which a hash index cannot.
Composite indexes and the leftmost prefix rule
An index on (user_id, created_at) is sorted by user_id first, then created_at inside each user. It serves: WHERE user_id = 5 (yes), WHERE user_id = 5 AND created_at > X (yes, and sorted for free), WHERE created_at > X alone (no: the index is not sorted by created_at globally). Column order in the index must match your query patterns, which is why "design indexes from queries, not from columns" is the rule.
Covering indexes and other accelerators
- Covering index: if the index contains every column the query needs, the DB never touches the table ("index-only scan"): the fastest read a B-Tree gives you.
- Partial index: index only
WHERE status = 'pending': tiny index for the hot subset. - Specialized: GiST/GIN for full-text, JSONB, geo; Bloom filters in Cassandra-land for "definitely not here" checks.
The costs (interviewers wait for this)
- Write amplification: 6 indexes = every INSERT does 7 writes. On write-heavy tables, indexes are a tax.
- Space and cache pressure: indexes compete with data for the buffer pool.
- Low-cardinality waste: an index on a boolean selects half the table: useless.
- Unused indexes: audit them (Postgres: pg_stat_user_indexes); drop what no query uses.
Worked example
Query: "a user's 20 most recent orders": WHERE user_id = 42 ORDER BY created_at DESC LIMIT 20. Index (user_id, created_at DESC): the DB walks straight to user 42's slice and reads 20 rows in order. Without it: full scan + sort of all orders. Verify with EXPLAIN: look for "Index Scan" not "Seq Scan".
Common interview traps
- "Add an index" without naming the query it serves.
- Composite index columns in the wrong order.
- Indexing everything on a write-heavy table.
- Never mentioning EXPLAIN: the tool that proves the index is used.
Interview Q&A
Q: Query was fast, got slow as the table grew, index exists. Why?
A: Check EXPLAIN: the planner may have abandoned the index (data distribution changed, stale statistics, or the query now returns a large fraction of the table where a seq scan wins). Also index bloat from churn. Fixes: ANALYZE/vacuum, rewrite the query, or a better-shaped index.
Q: B-Tree vs LSM-tree?
A: B-Trees (Postgres, InnoDB) update in place: great reads, random-write cost. LSM-trees (Cassandra, RocksDB, LevelDB) buffer writes in memory and flush sorted runs: great write throughput, reads may touch multiple files (compaction keeps it bounded). Write-heavy logs/events favor LSM; read-heavy relational workloads favor B-Trees.
Index asal mein hai kya
Bina index ke WHERE email = 'a@b.com' har row scan karta hai: 100M rows, 100M comparisons, seconds se minutes. Index ek auxiliary sorted data structure hai, usually B-Tree, jo indexed column ki values ko row locations se map karta hai. Lookup cost O(n) se ghatak O(log n): 100M rows ke liye ~27 comparisons, milliseconds. Keemat: extra disk, aur har write ab har index ko bhi update karti hai.
B-Tree intuition (aur zyadatar cheezon ke liye hash se behtar kyun)
Phone directory: names sorted hain, to "Sharma" dhoondna kuch page-splits ka kaam hai, poori reading nahi. B-Tree isse disk ke liye generalize karta hai: motte nodes (sainkdon keys each) taaki tree billions rows par bhi sirf 3-4 levels deep ho, aur har level ek disk page read hai. Kyunki ye sorted hai, range queries bhi deta hai (BETWEEN, >, ORDER BY, prefix LIKE 'abc%'), jo hash index nahi de sakta.
Composite indexes aur leftmost prefix rule
(user_id, created_at) ka index pehle user_id se sorted hai, phir har user ke andar created_at se. Ye serve karta hai: WHERE user_id = 5 (haan), WHERE user_id = 5 AND created_at > X (haan, aur sorting free), WHERE created_at > X akela (nahi: index globally created_at se sorted nahi hai). Index mein column order query patterns se match karna chahiye, isliye rule hai "indexes queries dekh kar banao, columns dekh kar nahi."
Covering indexes aur baaki accelerators
- Covering index: agar index mein query ke saare needed columns hain, DB table chhoota hi nahi ("index-only scan"): B-Tree ki fastest read.
- Partial index: sirf
WHERE status = 'pending'index karo: hot subset ke liye chhota index. - Specialized: full-text, JSONB, geo ke liye GiST/GIN; Cassandra duniya mein Bloom filters "yahan pakka nahi hai" checks ke liye.
Keemat (interviewers isi ka intezaar karte hain)
- Write amplification: 6 indexes = har INSERT par 7 writes. Write-heavy tables par indexes ek tax hain.
- Space aur cache pressure: indexes buffer pool mein data se jagah maangte hain.
- Low-cardinality bekaar: boolean par index aadhi table select karta hai: useless.
- Unused indexes: audit karo (Postgres: pg_stat_user_indexes); jo koi query use nahi karti, drop karo.
Worked example
Query: "user ke 20 latest orders": WHERE user_id = 42 ORDER BY created_at DESC LIMIT 20. Index (user_id, created_at DESC): DB seedha user 42 ke slice par jaati hai aur order mein 20 rows padhti hai. Bina iske: saare orders ka full scan + sort. EXPLAIN se verify karo: "Index Scan" chahiye, "Seq Scan" nahi.
Common interview traps
- "Index laga do" bina bataye kaunsi query ke liye.
- Composite index mein columns galat order mein.
- Write-heavy table par sab kuch index karna.
- EXPLAIN ka zikr kabhi na karna: wo tool jo prove karta hai index use ho raha hai.
Interview Q&A
Q: Query fast thi, table badhi to slow ho gayi, index maujood hai. Kyun?
A: EXPLAIN dekho: planner ne index chhod diya hoga (data distribution badli, statistics stale, ya query ab table ka bada hissa return karti hai jahan seq scan jeet-ta hai). Churn se index bloat bhi ho sakta hai. Fixes: ANALYZE/vacuum, query rewrite, ya better-shaped index.
Q: B-Tree vs LSM-tree?
A: B-Trees (Postgres, InnoDB) in-place update karte hain: great reads, random-write cost. LSM-trees (Cassandra, RocksDB, LevelDB) writes memory mein buffer karke sorted runs flush karte hain: great write throughput, reads multiple files chhoo sakti hain (compaction bounded rakhta hai). Write-heavy logs/events ke liye LSM; read-heavy relational ke liye B-Tree.