Ek B-tree index tumhe binary-search-jaisi lookups karne deta hai: N rows scan karne (O(N)) ki jagah, tum ek balanced tree mein O(logN) mein descend karte ho.
Lekin do problems abhi bhi rehti hain:
Multi-condition filters. Ek query WHERE a=? AND b=? do alag indexes par sirf ek ko efficiently use kar sakti hai, phir baaki ko filter karna padta hai. Ek composite (a,b) index dono ko ek saath narrow kar deta hai.
Extra fetch. Index matching row pointers find karne ke baad bhi, DB ko table par jaana padta hai doosre columns padhne ke liye jo tumne maange the. Har row ke liye woh ek random I/O hai. Covering index woh step hata deta hai.
Kyun? Kyunki index lexicographically sorted hai. Sirf c2 jaanna (bina c1 ke) ek (last, first) phone book mein sirf first names jaanne jaisa hai — matching entries har jagah scattered hain, toh koi fast seek possible nahi hai.
Multiple columns par ek index jo lexicographically sorted store hota hai — pehle col1 se, phir equal col1 ke andar col2 se, etc.
Leftmost-prefix rule batao.
(c1,…,cn) par ek index tabhi usable hai jab query ek leftmost prefix (c1, ya c1+c2, …) constrain kare; prefix columns par equality, phir agle par ek range.
Index (a,b) WHERE b = 5 ko efficiently kyun serve nahi kar sakta?
Entries pehle a se sorted hain, toh ek given b value poore mein scattered hai — seek karne ke liye koi contiguous range nahi.
Covering index kya hota hai?
Ek index jisme query ke saare columns hain (filter + SELECT), taaki koi table fetch na ho aur index-only answer mile.
Equality vs range columns — ordering rule kya hai?
Equality-predicate columns pehle rakho, range/ORDER BY column aakhir mein, taaki tum seek karke order mein range-scan kar sako.
Postgres INCLUDE (cols) kya karta hai?
Columns ko leaf pages mein non-key payload ke roop mein add karta hai taaki index covering bane, bina searchable key bloat kiye.
Covering/wide indexes ka main downside kya hai?
Zyada storage aur slower writes (har modification index update karna padta hai); cache mein fit nahi ho sakta.
Har fetch scattered table pages par potential random I/O hai; index-only scan hazaron random reads avoid karta hai.
Recall Feynman: ek 12-saal ke bachche ko samjhao
Ek giant phone book imagine karo. Agar woh last name phir first name se sort hai, tum "Smith, Anna" super fast dhundh sakte ho. Lekin agar tum sirf "Anna" jaante ho (koi last name nahi), tumhe POORI book padhni padegi — isliye ek multi-column index ko tum chahta hai ki tum pehla column jaano. Ab imagine karo phone book har insaan ka phone number unke naam ke saath print bhi karti hai — phir tumhe unke ghar drive kar ke poochne ki zaroorat nahi. Woh printed-number trick ek covering index hai: jo kuch bhi chahiye woh sab wahin hai.