Sign in

Database Indexing & Query Optimization: A Complete Guide from Scratch

Understand how relational database indexes store data, accelerate lookups, and guide query planning across real-world systems.

MonksBit Desk

November 25, 2026 · 9 min read · 90 views

Read

Database indexing is the technique of maintaining auxiliary data structures alongside primary table storage to locate rows quickly without scanning every block on disk. Query optimization is the process where a database engine evaluates alternative execution plans for a given query and selects the one with the lowest estimated input/output and processing cost.

You will need. Basic knowledge of relational tables, rows, and primary keys · Familiarity with Big-O notation for time and space complexity · Basic Python syntax for reading data structure implementations

How well do you know this already?

The full lesson

Level 1 · Beginner: Core index mechanics and table scans

A database table without an index is stored as an unordered sequence of disk pages, often called a heap file. When a query searches for a specific value in such a table, the database must read every record from disk into memory. This complete inspection of every entry is called a full table scan.

An index avoids full scans by keeping a separate list of column values in sorted order, paired with a pointer to the exact row on disk. Because the index values are sorted, the engine can find the target value using binary search rather than checking every record sequentially.

Consider a small table of four users with primary keys: user 10 named Alice, user 40 named Bob, user 20 named Charlie, and user 30 named Diana. Stored in insertion order, finding Diana requires inspecting four rows. If an auxiliary sorted array of keys pairs each key with its row pointer, the search can inspect the midpoint first, discard half the entries immediately, and locate Diana in two comparisons.

Linear scan versus a sorted array index with binary search

import bisect# Heap table representation (unordered records)table = [    {"id": 10, "name": "Alice"},    {"id": 40, "name": "Bob"},    {"id": 20, "name": "Charlie"},    {"id": 30, "name": "Diana"},]def full_table_scan(records, target_id):    reads = 0    for row in records:        reads += 1        if row["id"] == target_id:            return row, reads    return None, reads# Constructing a simple sorted index: list of (key, row_index)index = sorted([(row["id"], i) for i, row in enumerate(table)], key=lambda x: x[0])index_keys = [k for k, _ in index]def indexed_lookup(records, idx, idx_keys, target_id):    pos = bisect.bisect_left(idx_keys, target_id)    if pos < len(idx_keys) and idx_keys[pos] == target_id:        row_ptr = idx[pos][1]        return records[row_ptr]    return Nonefound_row, scan_count = full_table_scan(table, 30)indexed_row = indexed_lookup(table, index, index_keys, 30)assert found_row == indexed_row

Key takeaways

  • Without an index, every row lookup requires scanning the entire table from start to finish.
  • An index duplicates search key values into an ordered structure that stores pointers back to the original rows.
  • Sorted key structures turn linear scan time into logarithmic lookup time.

Level 2 · Intermediate: B-tree structures and cost-based query planning

Sorted arrays are inefficient for dynamic databases because inserting or deleting an item requires shifting elements in memory and disk blocks. Production relational databases use B+ Trees instead. A B+ Tree is a self-balancing search tree where each node contains multiple keys and children, fitting cleanly into fixed-size disk blocks called pages.

In a B+ Tree, internal nodes store routing keys that direct searches down the tree hierarchy, while leaf nodes store all data keys, row pointers, and bidirectional links to adjacent leaf pages. These leaf links make sequential range scans, such as finding values between 20 and 50, fast and contiguous.

The query optimizer determines whether an index should actually be used. If a query filters on a column with low selectivity, such as a boolean flag where 95% of rows match, following index pointers to fetch random disk blocks is often slower than reading the whole table sequentially. The optimizer estimates the total disk input/output and CPU operations using stored table statistics before generating an execution plan.

In-memory B+ Tree leaf and node traversal simulation

class BPlusLeaf:    def __init__(self):        self.keys = []        self.values = []        self.next = Noneclass BPlusIndex:    def __init__(self, branching_factor=3):        self.branching_factor = branching_factor        self.root = BPlusLeaf()    def insert(self, key, value):        leaf = self._find_leaf(key)        pos = 0        while pos < len(leaf.keys) and leaf.keys[pos] < key:            pos += 1        leaf.keys.insert(pos, key)        leaf.values.insert(pos, value)        # Simplified demo without node splitting logic    def _find_leaf(self, key):        # For this minimal representation, root is the sole leaf        return self.root    def range_query(self, low, high):        leaf = self._find_leaf(low)        results = []        while leaf is not None:            for k, v in zip(leaf.keys, leaf.values):                if low <= k <= high:                    results.append(v)                elif k > high:                    return results            leaf = leaf.next        return resultsidx = BPlusIndex()idx.insert(10, {"id": 10, "name": "Alice"})idx.insert(20, {"id": 20, "name": "Charlie"})idx.insert(30, {"id": 30, "name": "Diana"})idx.insert(40, {"id": 40, "name": "Bob"})assert [r["name"] for r in idx.range_query(15, 35)] == ["Charlie", "Diana"]

Key takeaways

  • B+ Trees store routing keys in internal nodes and keep all actual records or row pointers in linked leaf nodes.
  • Leaf node linking enables efficient range queries without re-traversing the tree hierarchy.
  • The query optimizer compares estimated page read costs of an index scan versus a sequential scan before running a query.

Level 3 · Advanced: Composite indexing, covering indexes, and execution plans

Composite indexes cover multiple columns in a specified order, such as (department_id, salary). The index is sorted first by the first column and then by subsequent columns. Consequently, the index accelerates queries that filter by department_id alone or department_id and salary together, but cannot accelerate queries filtering only by salary. This is known as the leftmost prefix rule.

A covering index contains all columns requested by a query, including both filtered and projected fields. When an index covers a query, the storage engine retrieves required data directly from the leaf nodes of the B+ Tree, skipping the second step of dereferencing row pointers to read primary heap table pages. This avoids random disk I/O.

Index maintenance introduces write amplification. Every insert, update, or delete on a table must update every corresponding index structure, lock pages, and potentially trigger tree rebalancing operations. Designing an optimal indexing schema requires balancing read latency gains against write throughput penalties and disk footprint.

Cost-based execution plan selection between scan and index

class QueryOptimizer:    def __init__(self, total_rows, page_size=100):        self.total_rows = total_rows        self.page_size = page_size        self.pages = (total_rows + page_size - 1) // page_size    def estimate_cost(self, matched_rows, index_depth=3):        # Sequential scan reads every page sequentially (cost weight = 1.0 per page)        seq_scan_cost = self.pages * 1.0        # Non-covering index scan traverses tree, then does random heap read per row        # Random disk read weight = 4.0, index page read weight = 1.0        index_lookup_cost = index_depth * 1.0        heap_random_read_cost = matched_rows * 4.0        index_scan_cost = index_lookup_cost + heap_random_read_cost        chosen_plan = "INDEX_SCAN" if index_scan_cost < seq_scan_cost else "TABLE_SCAN"        return {            "seq_scan_cost": seq_scan_cost,            "index_scan_cost": index_scan_cost,            "chosen_plan": chosen_plan        }optimizer = QueryOptimizer(total_rows=100000, page_size=100)# Highly selective query: 10 rows matchhighly_selective = optimizer.estimate_cost(matched_rows=10)assert highly_selective["chosen_plan"] == "INDEX_SCAN"# Low selectivity query: 20,000 rows matchlow_selectivity = optimizer.estimate_cost(matched_rows=20000)assert low_selectivity["chosen_plan"] == "TABLE_SCAN"

Key takeaways

  • Composite indexes enforce the leftmost prefix rule; column order dictates query compatibility.
  • Covering indexes satisfy queries entirely from index leaf nodes without inspecting table heap pages.
  • Indexes improve read query performance at the direct expense of write latency and storage overhead.

Complexity

  • Time: Best: O(1), Average: O(log N), Worst: O(log N) for B+ Tree index lookup; O(N) for full table scan
  • Space: O(N) auxiliary space where N is the number of indexed records

Traversing a balanced B+ Tree of N records takes logarithmic time proportional to tree depth. Auxiliary space is linear because every indexed row has a corresponding entry stored across the index leaf nodes.

Common mistakes

  • Applying functions or calculations to indexed columns in WHERE clauses (such as WHERE YEAR(created_at) = 2024), which prevents the optimizer from using the index.
  • Ignoring column ordering in composite indexes, resulting in secondary columns being unusable when earlier columns are omitted in filters.
  • Over-indexing tables by creating redundant single-column indexes on every field, significantly degrading INSERT and UPDATE performance.
  • Assuming an index will always be chosen by the query optimizer even when matching a large percentage of total rows.

Practice problems

  1. Leftmost prefix verification (easy). Hint: Check whether queries match column definitions starting strictly from index column zero without skipping positions.
  2. Design a covering index (medium). Hint: Identify both filter conditions in WHERE and projection targets in SELECT so heap page reads are eliminated.
  3. Cost model selectivity threshold (hard). Hint: Calculate the exact percentage of rows where random page fetch costs equal full sequential scan page read costs.

Summary

Database indexing replaces expensive linear table scans with efficient logarithmic B+ Tree lookups. The query optimizer estimates I/O costs using table statistics to choose between index traversals and sequential scans. By carefully ordering composite keys and designing covering indexes, systems achieve high read performance while controlling write amplification.

Finish the Prove step above to complete this lesson.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!