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.6 How do you know whether a query uses an index?
3 min read+10 XP
In a book: You can't always tell from the outside how someone found a page. So you ask them: "did you use the index, or flip through?"
In the system: Ask the database with EXPLAIN. It shows the query plan: the steps the planner chose.
EXPLAIN QUERY PLAN SELECT id, total FROM orders WHERE user_id = 7; -- SQLite
before the index: SCAN orders
after the index: SEARCH orders USING INDEX idx_orders_user (user_id=?)
What to look for, in any database:
- Scan of a big table where you expected a search/seek: the index isn't being used.
- Index-only / covering scans: good.
- Sort steps on big results: a composite index might avoid them.
- Estimated vs actual rows (PostgreSQL's
EXPLAIN ANALYZEactually runs the query and shows both): a big gap means the planner's statistics are stale or misleading, and it may be choosing badly.
Why the planner might skip your index: the table is small; the condition matches a large share of rows; statistics are out of date; or the query is written so the index can't be used (a function on the column, a leading %, a type mismatch; see 9.8 and the Level 4 bug).
Make it a habit: EXPLAIN every new query that runs often, and look at the slow-query log regularly.
Memory code: "Don't guess, EXPLAIN."