Skip to content
Chethan Yadav_
Database Management Systems

DBMS/Lesson 8 of 9/6 min read

Indexing, B+ Trees and Query Processing

File organization, primary, clustered, secondary and dense/sparse indexes, B-trees vs B+ trees, hash indexes, composite and covering indexes, when not to index, and query optimization basics.


On this page

Why indexing

Without an index, finding rows means a full table scan: reading every block, O(n). An index is an extra data structure that maps search key values to row locations, like the index at the back of a book. It makes lookups O(log n) at the cost of extra storage and slower writes.

File organization

  • Heap file: rows stored in insertion order. Fast inserts, slow searches.
  • Sorted (sequential) file: rows sorted by a key. Binary search possible, inserts expensive.
  • Hashed file: a hash function on a key decides the block. Fast equality lookups.

Database Index types

Primary index vs secondary index

  • Primary index: on the key the file is sorted by (often the primary key). One per table.
  • Secondary index: on any other column; the file is not sorted by it. Many allowed.

Clustered Index

A clustered index determines the physical order of rows on disk; the leaf level is the data. Only one per table. Range queries on the clustered key are very fast (rows are adjacent).

In MySQL InnoDB the primary key is always the clustered index. PostgreSQL tables are heaps; CLUSTER reorders once but is not maintained.

Non-Clustered Index

A non-clustered index is a separate structure whose leaves hold the key plus a pointer to the row (a row id, or in InnoDB the primary key value, which needs a second lookup). Many per table.

Dense Index

A dense index has an entry for every search key value (every row). Fast lookups, more space. Secondary indexes must be dense.

Sparse Index

A sparse index has entries for only some values, typically one per data block (the first key in each block). Find the largest entry <= the key, then scan that block. Needs the file to be sorted on the key, so only possible for primary/clustered indexes.

Multilevel index: when an index itself is too large, build a sparse index on the index. This idea leads directly to B+ trees.

B-Tree

A B-Tree of order m is a self-balancing multiway search tree:

  • Each node has at most m children and m - 1 keys.
  • Each non-root internal node has at least ceil(m/2) children.
  • All leaves are at the same depth.
  • Keys and data pointers are stored in both internal nodes and leaves.

Height is O(log_m n). With m in the hundreds (one node = one disk page), a billion rows need only 3 to 4 levels, so 3 to 4 disk reads.

B+ Tree

A B+ Tree is the variant used by almost every relational database index:

  • Internal nodes store only keys (routing information), not data pointers, so they fit more keys: higher fan-out, shorter tree.
  • All data pointers (or rows) are in the leaves.
  • Leaves are linked in a doubly linked list, so range scans walk leaves sequentially.
                [ 30 | 60 ]
               /     |     \
       [10|20]    [40|50]    [70|80]
          |          |          |
 leaves: 10 20 <-> 30 40 50 <-> 60 70 80   (linked)

B-Tree vs B+ Tree

B-TreeB+ Tree
Data in all nodesData only in leaves
Search may end at an internal nodeSearch always goes to a leaf
Range query needs tree traversalRange query follows leaf links
Lower fan-outHigher fan-out, shallower
No key duplicationInternal keys repeated in leaves

Insertion: insert into a leaf; if it overflows, split it and push the middle key up, possibly splitting up to the root (the only way the tree grows taller). Deletion: remove from the leaf; if it underflows, borrow from a sibling or merge.

LSM trees (RocksDB, Cassandra) are the main alternative for write-heavy workloads; see NoSQL.

Hash Index

A hash index computes hash(key) to find a bucket. O(1) average for equality lookups, but useless for range queries, sorting or prefix matching. Collisions handled with overflow chains. Extendible and linear hashing let the table grow without rehashing everything. See hash tables.

Composite Index

A composite (multi-column) index on (last_name, first_name, age) is sorted by last_name, then first_name, then age.

Leftmost prefix rule: it helps queries filtering on last_name, or last_name + first_name, or all three, but not on first_name alone. Put the most selective, most frequently filtered, equality columns first; range columns last.

Covering Index

A covering index contains every column a query needs, so the database answers from the index alone (an index-only scan) without touching the table.

CREATE INDEX idx_orders_user ON orders (user_id, created_at) INCLUDE (total);
SELECT created_at, total FROM orders WHERE user_id = 5;   -- index only

When indexes hurt or are ignored

  • Every INSERT, UPDATE, DELETE must update every index: write cost and storage.
  • Low-selectivity columns (boolean is_active) rarely benefit.
  • Functions on the column defeat the index: WHERE LOWER(email) = '[email protected]' needs an expression index.
  • Leading wildcard: LIKE '%abc' cannot use a B+ tree.
  • Implicit type casts (comparing a string column to a number).
  • Small tables: a full scan is cheaper.

Query processing

  1. Parsing and translation: SQL to a relational algebra tree; check syntax and that tables exist.
  2. Optimization: generate equivalent plans and choose the cheapest using statistics (row counts, value distribution).
  3. Execution: the engine runs the chosen plan.

Query Optimization

  • Heuristic (rule-based): push selections and projections down (filter early), replace a Cartesian product plus selection with a join, join smaller results first.
  • Cost-based: estimate I/O and CPU for each plan using statistics and pick the cheapest. Join ordering is the hardest part (exponential choices, so dynamic programming or heuristics).

Join algorithms:

AlgorithmIdeaGood when
Nested loopFor each outer row, scan innerSmall inner table or indexed inner
Index nested loopUse an index on the inner join keySelective lookups
Sort-mergeSort both inputs, mergeInputs already sorted, range joins
Hash joinBuild hash table on smaller input, probe with largerLarge equi-joins

Execution Plan

Use EXPLAIN (or EXPLAIN ANALYZE to actually run it) to see the execution plan:

EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = 5 ORDER BY created_at DESC LIMIT 10;

Look for sequential scans on large tables, bad row estimates, sorts that spill to disk, and nested loops over large inputs.

Quick revision

  • Clustered index = physical order, one per table; non-clustered = separate, many.
  • Sparse needs sorted data; dense has an entry per row.
  • B+ tree: data only in leaves, linked leaves, high fan-out, great for ranges.
  • Hash index: equality only.
  • Composite index follows the leftmost prefix rule.