Belajar
← All lessons

How database indexes work

Find a user by email

Email to findSearch withNo indexIndex
Table users
Index users_email_idx
no index
index

With 1,000,000 rows, a scan reads 1,000,000. The tree reads about 4 pages

scan.js

// no index: read every row and compareconst matches = [];for (const row of readAllRows("users")) {  if (row.email === email) matches.push(row);}

index.js

await db.query("CREATE INDEX users_email_idx ON users (email)"); // with the index: walk the tree, then read one rowconst entry = walkTree(usersEmailIdx, email);const row = entry && readRow(entry.rowId);

Walk the B-tree one page per level

Root
Inner
Leaf
Table

btree.js

function findByEmail(email) {  let page = readPage(index.root);  while (!page.isLeaf) {    const i = page.keys.findIndex((k) => email < k);    page = readPage(page.children[i < 0 ? page.keys.length : i]);  }  const entry = page.entries.find((e) => e.key === email);  if (!entry) return null;  return readRow(entry.rowId);}

Every insert updates the index too so writes get slower

New user's emailIndexes on usersNoneemailThree
Where the row goes
Pages written

Each index makes some reads faster and every write slower

insert.js

await db.query("INSERT INTO users (email) VALUES ($1)", [email]); // what the database does for that one rowconst rowId = table.append(row);for (const index of table.indexes) {  const leaf = index.findLeaf(row[index.column]);  leaf.insert(row[index.column], rowId);  if (leaf.isOverFull()) index.split(leaf);}

An index helps only its own column and EXPLAIN tells you

Query byemail =name =email LIKEIndexesemailemail + name
Query users has 100,000 rows
Query plan

query.sql

CREATE INDEX users_email_idx ON users (email);// only with "email + name"CREATE INDEX users_name_idx ON users (name); EXPLAIN SELECT * FROM users WHERE email = 'dewi@mail.test';EXPLAIN SELECT * FROM users WHERE name = 'Dewi';EXPLAIN SELECT * FROM users WHERE email LIKE '%@work.test';

Topics

Next: How the JavaScript event loop works

Open lesson