← Back to all publications

Database Indexing Fundamentals: How B-Trees and LSM-Trees Power Queries

An engineering analysis of primary indexing structures: balanced search trees, write amplification in LSM-trees, and crafting optimal composite indexes.

B-TREE (POSTGRESQL / SQLITE) [ 20 | 50 | 80 ] < 20 20 .. 50 > 50 ✓ Predictable O(log N) Reads (1-3 Hops) • Random I/O on in-place page writes LSM-TREE (ROCKSDB / CASSANDRA) 1. MemTable (In-Memory Red-Black Tree) 2. Immutable SSTables (Append-Only Log) ✓ High Write Throughput (Sequential I/O) • Compaction overhead on background disk passes Storage Engine Tradeoff: Read Optimization vs. Write Amplification B-Trees prioritize low read latency • LSM-Trees prioritize high-volume sequential writes

The Mechanical Reality of Disk and Memory Access

At their core, database indexing algorithms are optimizations designed to minimize disk I/O and cache misses. When a relational database performs a sequential table scan, it reads every block on disk sequentially. An index creates an auxiliary data structure that reduces lookup complexity from O(N) to O(log N).

B-Trees vs. LSM-Trees: Tradeoffs Decoded

Characteristic B-Tree (PostgreSQL, MySQL, SQLite) LSM-Tree (RocksDB, Cassandra, LevelDB)
Read Latency Low and predictable (1-3 pointer hops) Higher (requires checking memtable & SSTables)
Write Throughput Moderate (random writes to pages) Extremely high (sequential log appends)
Storage Overhead Higher fragmentation over time Compact due to periodic compaction passes

The Leftmost Prefix Rule in Composite Indexes

When creating a multi-column index such as CREATE INDEX idx_users_org_role ON users (org_id, role, created_at);, column order is paramount. The database can efficiently resolve queries filtering on:

  • org_id
  • org_id AND role
  • org_id AND role AND created_at

However, querying on role or created_at alone bypasses the index entirely because the search tree was branched primarily on org_id.

HB

Written by HB

Writing on systems programming, backend architectures, and modern web engineering.

Continue Reading

Cloud Infrastructure

Architecting Distributed State at the Edge with Durable Objects

2026-09-01 • 7 min read
TypeScript

Mastering TypeScript Generics: Patterns for Robust, Type-Safe Systems

2026-09-05 • 6 min read