# Topic 42: Database Indexing
B-Tree page structures, Hash indexes, composite indexes, the leftmost prefix rule, and index write amplification.
1. Definition
A database index is an auxiliary on-disk search structure (predominantly a balanced B+ Tree) that allows the storage engine to locate specific rows in O(log N) time without scanning the entire table.
2. Explain Like I'm 5
An index is the alphabetical index at the back of a 1,000-page textbook. Instead of reading every page from page 1 to 1,000 to find "Photosynthesis", you look in the index, find "page 432", and turn directly to it.
3. Animation & Visual Simulation
Interactive Engine TraceDatabase Indexing Visual Simulator
CREATE INDEX idx_customers_country_city ON customers(country, city);
SELECT * FROM customers WHERE country = 'India' AND city = 'Bangalore';Active InputStep 1: Input & Parsing Stage
Initiating Database Indexing
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Looking up a user by email among 50 million records.
| Metric | Without Index (Seq Scan) | With B-Tree Index |
|---|---|---|
| Algorithm | O(N) linear scan | O(log N) tree traversal |
| Disk Pages Read | 500,000 8 KB pages | 3 to 4 index pages |
| Execution Time | 4,500 ms | 0.05 ms |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectCREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_status ON orders(user_id, status);
CREATE UNIQUE INDEX idx_users_uuid ON users(uuid);
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| B-Tree Balance | All leaf pages in a B+ Tree reside at the exact same depth from the root. |
| Leftmost Prefix Rule | A composite index on (A, B) can accelerate queries on (A) or (A, B), but CANNOT accelerate queries filtering solely on (B). |
| Write Amplification | Every INSERT, UPDATE, or DELETE on a table requires updating every index on that table. |
| B+ Tree fanout and height | 8 KB B+ Tree pages store hundreds of keys per page, keeping tree height shallow (3 to 4 levels for 100M rows). |
| Leftmost prefix rule for compound indexes | A composite index on (A, B, C) can satisfy queries filtering on (A), (A, B), or (A, B, C), but NOT (B) or (C) alone. |
7. Deep Dive: B+ Tree Page Split Mechanics & Write Penalty
When an index leaf page fills up (typically 8 KB), inserting a new key causes a page split: the engine allocates a new page, moves half the keys over, and inserts a routing key into the parent branch page. This causes write amplification and fragmentation if insertions are random (like UUIDv4).
-- Prefer sequential keys (IDENTITY, BIGINT, UUIDv7) over random UUIDv4: -- Random UUIDv4 causes random page writes and catastrophic cache eviction.
8. Advantages & Disadvantages
Advantages
- •Transforms O(N) full table scans into O(log N) point lookups.
- •Enforces uniqueness and powers foreign key checks.
Disadvantages & Trade-offs
- •Consumes additional disk and RAM.
- •Slows down INSERT, UPDATE, and DELETE operations.
9. Common Interview Questions
Q1.Explain the internal B+ Tree structure: Root, Branch, Leaf Pages, and Leaf Linked Lists.
A B+ Tree is a balanced multi-way search tree where all leaf pages reside at the exact same depth. Internal nodes (Root and Branch pages) store routing keys and 4-byte page pointers. Leaf pages store the actual index keys and 6-byte heap tuple pointers (CTID). Unlike standard B-Trees, data is stored ONLY in leaf pages, and all leaf pages are doubly linked in sorted order, enabling fast point lookups (O(log N)) and sequential range scans.
Q2.What causes B-Tree Page Splits and how do they lead to index fragmentation?
When a new key is inserted into a full 8 KB leaf page, the page cannot hold the new entry. The engine must allocate a new 8 KB page, move half the keys to the new page, and insert a new routing key into the parent branch page. Frequent page splits caused by random keys (like UUIDs) leave index pages half-empty (50% fillfactor), wasting RAM and disk space.
Q3.What is the Leftmost Prefix Rule for composite (multi-column) indexes?
A composite B-Tree index on (country, status, created_at) sorts keys first by country; within identical countries, it sorts by status; within identical statuses, by created_at. A query filtering on (country) or (country, status) can navigate the B-Tree directly. A query filtering on status alone cannot use the index because keys are sorted primarily by country first.
Q4.What is the difference between B-Tree, Hash, GIN, and GiST indexes in PostgreSQL?
1. B-Tree: Default balanced tree for equality (=) and range queries (<, >, BETWEEN). 2. Hash: O(1) in-memory hash lookup for equality (=) only. 3. GIN (Generalized Inverted Index): Maps composite elements (array values, JSONB keys, text lexemes) to rows; ideal for tags, full-text search, and JSONB. 4. GiST (Generalized Search Tree): Balanced tree for geometric, geospatial (PostGIS), and range types.
Q5.Why does adding an index speed up reads but slow down writes (INSERT, UPDATE, DELETE)?
Every time a row is inserted, the engine must write the row to the heap page AND traverse every single index B-Tree on that table to insert index keys into leaf pages. If a table has 10 indexes, one INSERT causes 11 disk writes! Updates to indexed columns also require updating the corresponding index B-Trees.
10. Interview-Ready Answer
“Database indexes are balanced search structures (primarily B+ Trees) that reduce lookup complexity from O(N) to O(log N). Engineers must design composite indexes around the Leftmost Prefix rule while balancing write amplification against read performance.”
11. Quick Test
Given an index on (country, status, created_at), which query CANNOT use this index efficiently?