9. Indexes
1
The picture to keep in your head2
9.1 What is an index, exactly?3
9.2 What's the difference between a full table scan and an index lookup?4
9.3 What does an index look like inside?5
9.4 How do composite indexes work, and what is the leftmost-prefix rule?6
9.5 What is a covering index?7
9.6 How do you know whether a query uses an index?8
9.7 What does an index cost you?9
9.8 When does an index not help, or even hurt?10
Memory card and where the analogy breaks11
Practice: five levels12
Interview questions13
Solutions14
Sources15
Code lab9. Indexes
9.8 When does an index not help, or even hurt?
3 min read+10 XP
In a book: An index entry for "the" would list every page: useless. An index can't help you find "every word ending in -ing", because it's sorted by how words start. And a tiny 4-page pamphlet doesn't need an index at all.
In the system: Common cases:
- Low selectivity. An index on
statuswith 3 values matches about a third of the table for each value. Fetching a third of the rows one by one through an index can be slower than one scan, so the planner often ignores it. Indexes shine when a condition matches a small fraction of rows. - Functions on the column.
WHERE lower(email) = 'asha@example.com'can't use an index onemail, because the index is sorted byemail, notlower(email)(the Level 4 bug). Fix: an expression index onlower(email), or store emails already lowercased. - Leading wildcards.
WHERE title LIKE '%systems%'can't use a B-tree, because it's sorted by how titles start. That's a job for a search index (Chapter 19). - Type mismatches. Comparing a text column to a number may force a conversion on every row and skip the index.
- Small tables. A scan of a few hundred rows is already fast.
- Write-heavy tables with indexes nobody uses. All cost, no benefit (9.7).
- Wrong column order in a composite index (9.4).
Memory code: "Indexes help when you look up a few, by how the column starts."