๐ 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.
- The book has thousands of pages in no particular order. You want every page that mentions "Zoe".
- With no index, you turn every single page, start to end.
- You found Zoe on page 3, but you still had to check the rest in case she appears again.
- The index at the back of the book is sorted. First you check, is Zoe in AโM or NโZ?
- NโZ. You go straight to that index page, skipping half the index.
- The index page says Zoe is on page 3. You turn straight there.
- Every new page means updating every index too. Lots of indexes make writing slower.
- 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.
- 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.