Topic B2
Database indexes
Why slow queries read the whole table, and how a B-tree index fixes it.
Watch: without an index, every row is read one by one. With an index, the computer goes straight to the rows it wants.
- being checked
- finished / the result
- no longer used
Like the index at the back of a book
Finding "recursion" in a 500-page book with no index means turning every page. The index at the back lists words alphabetically, each with its page numbers. You find the word in seconds, then go straight to the page. A database index works exactly the same way: sorted, small, and pointing at where the real data lives.
When an index gets used
- WHERE column = value and ranges (
>,<,BETWEEN). - ORDER BY column LIMIT n: the data is already sorted in the index, so no sort is needed.
- JOIN: foreign key columns like
orders.user_idalmost always need an index. PostgreSQL doesn't create one for you.
Code, for programmersCreating an index, then checking it's used
CREATE INDEX idx_orders_user ON orders (user_id);
EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = 42;
-- before: Seq Scan on orders (rows=10000000) ~1200 ms
-- after: Index Scan using idx_orders_user ~0.1 ms
-- composite index: filter by user, newest first
CREATE INDEX idx_orders_user_created ON orders (user_id, created_at DESC);When an index doesn't get used
- The column is wrapped in a function:
WHERE lower(email) = …can't use a plain index onemail. Indexlower(email)instead. - LIKE with a leading wildcard:
'%gmail.com'has no prefix to look up in sorted data. - Column order in a composite index: an index on
(user_id, created_at)helps filtering byuser_id, but not bycreated_atalone. Like a phone book sorted by surname, then first name. - Almost every row matches: if the query takes 60% of the table, reading the table directly is faster, and the database knows it.
Quiz
A 10-million-row table with no index on user_id. How many rows does WHERE user_id = 42 read?
An index on (user_id, created_at). Which query does it not help?
What is the main cost of an index?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.