Lesson 2 · Unit 02
Composite indexes
Column order decides which queries an index can serve
What you practise
- Column order and the leftmost-prefix rule, equality before range, covering indexes, when an index is ignored (functions on the column, leading
%, low selectivity)
Try a question from this lesson
Pick one
A phone book is sorted by last name, then first name. Which lookup can NOT use that order and has to read every page?
Correct answer
Everyone whose first name is Ann
Why
The Anns are scattered through the whole book: one under Adams, one under Baker, one under Smith. Sorting by two things only helps if you know the first thing.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
An index on two columns
An index on (city, age) is sorted by city first, then by age inside each city. Exactly like the phone book.
It serves any query that pins down a leftmost prefix of its columns: city alone, or city and age. For age alone it is useless: the 30-year-olds are scattered across every city.
CREATE TABLE users(id, city, age, name);
CREATE INDEX idx_city_age
ON users(city, age);Concept
When an index is ignored
An index helps only when the database can use its sort order.
Wrap the column in a function, like lower(email), and the sorted values no longer match what you ask for. Start a pattern with a wildcard, like '%@x.io', and there is no prefix to search by.
And when most rows match anyway, reading the whole table beats hopping through the index one row at a time.
9 more exercises in the app
- 4× multiple choice
- 2× type the answer
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.