How does a B-tree index speed up a lookup, and when does it not help?
basicA B-tree keeps keys sorted in a shallow, wide tree, so an equality or range lookup costs O(log n) page reads (usually 3-4 levels even for hundreds of millions of rows) instead of scanning the whole table. It also returns rows in key order, which can eliminate a sort.
- It helps for
=,<,>,BETWEEN,IN, prefixLIKE 'abc%',ORDER BYandMIN/MAX. - It does not help when the predicate matches a large fraction of rows (the planner prefers a sequential scan), on tiny tables, or when the predicate is not sargable.
- Every index costs write amplification (each INSERT/UPDATE/DELETE maintains it), disk and buffer-pool space.
- Does an index on a boolean/low-cardinality column help? Rarely on its own; it can help if one value is very rare (
WHERE status = 'FAILED'), ideally as a partial index. - Is the primary key index different in MySQL InnoDB? Yes, InnoDB stores rows in the clustered PK B-tree; secondary indexes hold the PK value and need a second lookup. PostgreSQL tables are heaps and all indexes point to a tuple id.