Skip to the guide

Indexes: how databases find data

IntermediateConcept3 pages

An index is a second, sorted copy of a few columns that lets the database jump to the rows it needs instead of reading the whole table. Interviewers expect you to name the index behind every hot query in your design, put its columns in the right order, and say what each index costs on writes.

The index at the back of a cookbook

A big cookbook has 900 recipes. To find every recipe with lentils, you could read all 900, or turn to the sorted index at the back: "lentils: 112, 240, 618". A second index, by cuisine and then by cooking time, finds "Indian dishes under 30 minutes" in one place, and if each entry also lists the time, you don't need to open the recipes at all. The price: every new edition means updating every index, and the indexes take pages of their own.

  • reading all 900 recipes → a full table scan
  • the index at the back → a secondary index: sorted keys, each pointing at a row
  • by cuisine, then time → a composite index: sorted by the first column, then the second within it
  • entries that carry the cooking time → a covering index: the query never opens the table
  • updating every index each edition → the write cost of indexes