TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

โ† Back to Database indexes

๐Ÿ“‘ Database indexes: cheat sheet

๐ŸŽจ The analogyThe index at the back of a book: look the word up and turn straight to its page.
๐ŸŽ“ The regular explanationSorted lookup structures, usually B-trees, that let a database find rows in a few page reads instead of scanning the whole table. They speed up reads and cost extra work on every write.
Reading every pageStep 3 of 3
The book's pagesanakey ana@x.io: ana0tomkey tom@x.io: tom1zoekey zoe@x.io: zoe2bobkey bob@x.io: bob3cykey cy@x.io: cy4evekey eve@x.io: eve567reading๐Ÿง’You
  1. The book has thousands of pages in no particular order. You want every page that mentions "Zoe".
  2. With no index, you turn every single page, start to end.
  3. You found Zoe on page 3, but you still had to check the rest in case she appears again.
Looking it up in the indexStep 3 of 3
๐Ÿง’You๐Ÿ—‚๏ธ Index: Aโ€“M or Nโ€“Z?๐Ÿ“‘ Index page Aโ€“M๐Ÿ“‘ Index page Nโ€“Zzoe โ†’ page 3๐Ÿ“„ Page 3
  1. The index at the back of the book is sorted. First you check, is Zoe in Aโ€“M or Nโ€“Z?
  2. Nโ€“Z. You go straight to that index page, skipping half the index.
  3. The index page says Zoe is on page 3. You turn straight there.
Indexes cost something tooStep 3 of 3
โœ๏ธWriter๐Ÿ“„ The pages๐Ÿ“‘ Name indexIndex Scan โœ“๐Ÿ“‘ Town indexcity first
  1. Every new page means updating every index too. Lots of indexes make writing slower.
  2. An index sorted by town, then age, helps "people in Leeds aged 30". It doesn't help "everyone aged 30", because ages are scattered across towns.
  3. To know whether an index is being used, ask the librarian to describe how they'll look something up.

๐Ÿงฉ Key questions

Without an index, how do you find every mention of Zoe?
Turn every page, start to finish. Even after finding her, you keep going in case she appears again.
Why can you find Zoe in the index with just a few looks?
The index is sorted, so each look narrows it down. Aโ€“M or Nโ€“Z? Nโ€“Z. Then straight to the right page.
The index is sorted by town, then age. Which question does it help with?
People in Leeds aged 30. Sorted by town first, so you need the town to start.