ENES

Database index

A sorted shortcut that lets a database find rows without reading the whole table.

On the left, a long table read row by row from top to bottom; on the right, a small tree that reaches the right row in three jumps

A database index is an extra structure, kept next to a table, that lets the database jump straight to the rows you ask for. Without one, a query like 'find the customer with email [email protected]' forces a full scan: reading every row until it shows up. With an index on the email column, the database looks the value up in a sorted structure and goes directly to the right row.

Most indexes are a B-tree: a sorted, branching structure where each step narrows the search, so finding one value among a hundred million takes a handful of jumps instead of a hundred million reads. You create one with a line of SQL, CREATE INDEX ON customers (email);, and from then on the database keeps it up to date by itself and decides when to use it.

Indexes are not free. Each one takes disk space, and every insert or update has to update the indexes too, so writes get slower. The craft is choosing them from the queries the app really runs: the columns used to filter, join and sort. When a page that used to load instantly starts taking seconds as the data grows, a missing index is the first suspect.

Keep in mind

Go deeper

Related terms

More in Data