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

All concepts ยท databases ยท sql ยท performance

Database indexes

Sorted 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.

9 min3 animations

๐Ÿ–จ๏ธ Cheat sheet

Reading every page

A huge book has its pages in no particular order. To find every mention of "Zoe" you'd have to turn every page, from start to finish, and even after finding her you'd keep going in case she appears again.

Full table scans

Rows are stored roughly in insertion order. A query like WHERE email = 'zoe@x.io' on an unindexed column needs a full table scan (Postgres calls it Seq Scan): read every row and test it. That's fine for a thousand rows and painful for fifty million, and it gets slower as the table grows.

Reading every page3 steps
The book's pages01234567๐Ÿง’You
Press play and watch it happen!

The index at the back

A book's index is sorted, so you never read it all. Is "Zoe" in Aโ€“M or Nโ€“Z? Nโ€“Z. Then the right page of the index, which says "page 3". Turn straight there. A few looks instead of thousands of pages.

B-trees

Most indexes are B-trees: balanced trees of sorted keys, each node one disk page holding hundreds of keys. A lookup walks from the root to a leaf, typically 3โ€“4 page reads even for hundreds of millions of rows (O(log n)). Leaves point to the row and are linked in order, so ranges (BETWEEN, >, ORDER BY) are fast too.

1CREATE INDEX idx_users_email ON users (email);

Primary keys and UNIQUE constraints get an index automatically. Foreign keys often don't, and usually should.

Looking it up in the index3 steps
๐Ÿง’You๐Ÿ—‚๏ธ Index: Aโ€“M or Nโ€“Z?๐Ÿ“‘ Index page Aโ€“M๐Ÿ“‘ Index page Nโ€“Z๐Ÿ“„ Page 3
Press play and watch it happen!

Indexes have a cost

Every new page means updating every index too, so too many indexes slow down writing. And an index sorted by town, then age, helps you find "people in Leeds aged 30", but not "everyone aged 30".

Trade-offs and composite indexes

Every index costs disk space and slows INSERT, UPDATE and DELETE. Add indexes for the queries you actually run.

A composite index on (city, age) is sorted by city, then age within each city. It serves filters on city, or on city and age, but not age alone (the leftmost-prefix rule). Put equality columns first, then range columns.

Check with EXPLAIN ANALYZE. Wrapping a column in a function (WHERE lower(email) = โ€ฆ) skips a plain index unless you index that expression.

Indexes cost something too3 steps
โœ๏ธWriter๐Ÿ“„ The pages๐Ÿ“‘ Name index๐Ÿ“‘ Town index
Press play and watch it happen!
๐Ÿ”ง Going deeper

Covering indexes contain every column a query needs (INCLUDE in Postgres), so the table isn't touched at all.

Other kinds: hash indexes for equality only, GIN for full-text and JSON, GiST for geometry, and LSM trees in write-heavy stores like Cassandra and RocksDB.

๐Ÿงฉ Quick quiz

Quick quiz! 3 questions about Database indexes, told the same way as the story.
  1. Without an index, how do you find every mention of Zoe?
  2. Why can you find Zoe in the index with just a few looks?
  3. The index is sorted by town, then age. Which question does it help with?
Answer every question to check.Passing marks Database indexes as done.
Got the hang of Database indexes? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐ŸŽฏ Backend interview prepStep 1 of 9

Next on the path โ†’๐Ÿ›’ Transactions and isolation

๐Ÿ—ƒ๏ธ Spring and databasesStep 3 of 7

โ† Previous on the path๐Ÿ›’ Transactions and isolationNext on the path โ†’๐Ÿ“ Spring transactions (@Transactional)

๐Ÿ—๏ธ Storing data at scaleStep 1 of 7

Next on the path โ†’๐Ÿงญ Query planning and EXPLAIN

๐Ÿ‘‰ Read next

  • ๐Ÿ›’Transactions and isolationPaying at a till, where money leaves your purse and enters the till together or not at all.
  • ๐Ÿฝ๏ธThe N+1 query problem (JPA and Hibernate)A waiter who walks back to the kitchen once per diner for each side dish, instead of carrying one tray.
  • ๐Ÿ—‚๏ธLSM treesA journalist's in-tray: new notes go in a sorted tray, and full trays become folders that are never edited.
  • ๐ŸงญQuery planning and EXPLAINA sat-nav choosing a route from last week's traffic counts, and going badly wrong when those counts are stale.