How Indexes Work

B-Tree Indexes

Most indexes are B-trees: sorted, balanced trees where each lookup walks from the root to a leaf in a few steps. Finding one row among 10 million takes about 3 to 4 page reads instead of reading every row.

  • Great for =, <, >, BETWEEN, ORDER BY and prefix LIKE 'abc%'.
  • Not used for LIKE '%abc' (leading wildcard): there is no sorted prefix to search.
  • Other kinds exist: hash (equality only), full-text, GiST/GIN (PostgreSQL), bitmap (Oracle).

The Cost of an Index

Indexes are not free:

  • Every INSERT, UPDATE of an indexed column and DELETE must also update each index.
  • They take disk space and memory.
  • Too many indexes slow down writes and confuse the optimizer.

What Gets Indexed Automatically

Databases create an index automatically for every PRIMARY KEY and UNIQUE constraint. Foreign keys are not indexed automatically in PostgreSQL, SQL Server or Oracle (MySQL InnoDB does create one). Index them yourself, because joins use them all the time.