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.

Level: IntermediateWatch: 8 steps · ~1 minuteGrow the table, add an index, change the queryRecall: 3 questions · 8 cardsCompare 4 setupsPostgreSQL · MySQL · SQLite · TypeScript

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 with EXPLAIN

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
SELECT * FROM users WHERE email = 'mai@shop.test'no index yet
the app
users 1,000,000 rows · 1 window ≈ 10,000 rows
Find mai@shop.test → …
Step 1 / 8 · step by step
Seq ScanThe plan
1,000,000Rows read
0Pages read
0.00 msTime (simulated)
–Index size (rough)

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.

Step 4 · Every option at once, on one clock

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.

1,000 rows
No indexa Seq Scan every timefind 10 pages · 0.10 ms · INSERT 1 pages

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 rowReads every page: O(n)One page per level: O(log n)
Table 10× bigger10× slowerOften the same depth
INSERTWrites the tableWrites the table and every index
SpaceThe tableThe 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

users.pg.sql
-- 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';
Run: 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.

Read: an index is a sorted copy

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.

Read: when an index can't help

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.

Read: so which columns?

Next lesson

Scaling a databaseLevel: Deep

An index is the first move; next, what comes after when the database still can't keep up.