Database index
One email among a million rows. Without an index the database reads every page; with a B-tree it reads four. See both, grow the table to ten million, then find out what an index costs and when it can't help.
What you'll take away
- Explain why a B-tree finds a row in a few pages while a Seq Scan reads them all
- Know why a tree over ten times the rows is often no deeper: O(log n) vs O(n)
- Weigh what an index costs: every INSERT writes it too, and it takes disk and memory
- Fix a query that skips its index, like
lower(email), and check it withEXPLAIN
The 1-minute version
Tap a point and the picture below plays that step.
Try 1k against 10M with no index, then add the index on email. Then switch the query to lower(email). The numbers are the model's (100 rows a page, 300 keys an index page, 0.01 ms a page from memory), not measurements
A users table of a million rows, no index on email, and SELECT * FROM users WHERE email = 'mai@shop.test'. What does the database do?
The picture: the app at the front and the users table at the back, where each lit window is one stretch of its pages (the label says how many rows a window stands for). With no index the only way is the road round the side, and a lookup reads the table floor by floor (amber), passes the row it wants (teal) and still can't stop. CREATE INDEX puts up a tree between them: a root, three branches and six leaves, with the keys each one covers on its roof. A lookup takes the tree's short roads to one window. The numbers come from a model (100 rows a page, 300 keys an index page, 0.01 ms a page), not from a real database.
Compare them all: Database index
The same job in every tile: a users table growing from a thousand rows to ten million, and at each size one lookup by email and one INSERT. See which slows down with the table, and which pays on writes.
Use it when Small tables of a few hundred rows, or queries that read most of the table anyway
Skip it when A growing table you look up one row at a time: it slows down in step with the rows
A model: 100 rows a page, 300 keys an index page, 0.01 ms a page from memory (made-up figures, not measurements). Press any tile to see it large above, with when it fits.
Full scan or index?
| No index (Seq Scan) | B-tree index | |
|---|---|---|
| Find one row | Reads every page: O(n) | One page per level: O(log n) |
| Table 10× bigger | 10× slower | Often the same depth |
| INSERT | Writes the table | Writes the table and every index |
| Space | The table | The table plus each index |
An index is a sorted copy
An index keeps a column's values in order, with a pointer to each row. Because it's sorted, it also answers ranges (>, BETWEEN) and ORDER BY without sorting again. Because it's a copy, every write has to keep it up to date.
An index sorts once, so queries don't have to. How sorting itself works: Sorting.
When an index can't help
A function around the column (lower(email)), a LIKE '%mai' that starts with a wildcard, a two-column index searched by its second column only, or a column where most rows share the same value. And a small table is often faster to read whole; the planner knows that and will skip your index.
So which columns?
The ones your real queries search, join and sort by, starting with the most selective. Check with EXPLAIN before and after, and drop indexes nobody uses.
In real code
-- PostgreSQL 16: 100,000 users, then the same lookup before and after an index.
CREATE TABLE users (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL, name text NOT NULL);
INSERT INTO users (email, name)
SELECT 'user' || i || '@example.com', 'User ' || i FROM generate_series(1, 100000) AS i;
ANALYZE users;
-- 1. No index on email: the planner has to read the whole table (Seq Scan).
EXPLAIN (COSTS OFF) SELECT * FROM users WHERE email = 'user4242@example.com';
-- 2. A B-tree on email: a few pages down the tree, then the row (Index Scan).
CREATE INDEX users_email ON users (email);
EXPLAIN (COSTS OFF) SELECT * FROM users WHERE email = 'user4242@example.com';
-- 3. A function on the column: the index on email can't be used for lower(email).
EXPLAIN (COSTS OFF) SELECT * FROM users WHERE lower(email) = 'user4242@example.com';
-- 4. Index the expression itself, and it can.
CREATE INDEX users_lower_email ON users (lower(email));
ANALYZE users;
EXPLAIN (COSTS OFF) SELECT * FROM users WHERE lower(email) = 'user4242@example.com';
psql -f users.pg.sql (checked against PostgreSQL 16 in Docker)It printed:Seq Scan on users Filter: (email = 'user4242@example.com'::text) Index Scan using users_email on users Index Cond: (email = 'user4242@example.com'::text) Seq Scan on users Filter: (lower(email) = 'user4242@example.com'::text) Index Scan using users_lower_email on users Index Cond: (lower(email) = 'user4242@example.com'::text)
100,000 users, then the same lookup four times: no index, an index on email, lower(email) against that index, and an index on lower(email). Each engine really runs it (PostgreSQL 16 and MySQL 8.4 in Docker, SQLite with its CLI); below is what each printed. MySQL's access type ALL means the whole table, ref means through an index.
Common questions
What is a database index?
A sorted copy of a column's values, each with a pointer to its row. Because it's sorted, the database can walk down to the value instead of reading the whole table.
Why is a B-tree so fast?
One page holds hundreds of keys, so a million rows is only 3 levels deep, and a table ten times bigger is often the same depth. That's O(log n) against a full scan's O(n).
Why not index every column?
Every index is one more thing each INSERT, UPDATE and DELETE has to write, and it takes disk and memory. Five indexes means six writes per inserted row. Index what your real queries use.
I have an index. Why doesn't my query use it?
The usual reasons: a function around the column (lower(email)), a LIKE that starts with %, a two-column index searched by its second column only, or a value most rows share. On a small table the planner may simply read it all.
How do I make WHERE lower(email) = … use an index?
Index the expression itself: CREATE INDEX ON users (lower(email)). The index on email holds email, not lower(email), so it can't help that query.
Does an index help with ranges and ORDER BY?
Yes. A B-tree is already sorted, so it can find where a range starts (>, BETWEEN) and read on in order, and hand back ORDER BY without sorting again.
Which columns should I index, and how do I check it worked?
The ones your real queries search, join and sort by, the most selective first. Look at EXPLAIN before and after: Seq Scan reads the whole table, Index Scan walks the index. And drop indexes nobody uses.
Next lesson
Scaling a databaseLevel: Deep
An index is the first move; next, what comes after when the database still can't keep up.