> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How Database Indexing Works

> Explains why databases use indexes, how B-tree and clustered versus nonclustered indexes speed lookups, and the write and storage trade offs

How does database indexing actually work?

This lesson explains why databases use indexes and how indexes speed up lookups, with simple diagrams and practical notes on performance trade-offs.

Suppose we have a `users` table with nine users stored in the order they signed up, and we want to find the user named Nina. The simplest approach is a full table scan: the database checks every row one by one until it finds a match.

![A dark-themed image shows a left-side table listing numbered names (Maya, Leo, Sara, Ben, Nina, etc.) with corresponding cities. On the right is a highlighted search button labeled "NINA" above the text "FULL SCAN."](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Databases/How-Database-Indexing-Works/nina-full-scan-search-table.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=5ceb87df436f2484336329a3c38dc2fe)

Full table scans are fine for small tables but become impractically slow when millions of rows exist. Indexes are the data structure databases use to avoid scanning every row and to make lookups fast.

What is an index?

* An index is a separate, sorted data structure that stores the values of one (or more) columns you search on and pointers to the rows that contain those values.
* The original table remains in its physical order (e.g., sign-up order); the index is an auxiliary structure optimized for search.

For example, an alphabetical index on the `name` column might look like:

* `Ava -> row 7`, `Ben -> row 4`, `Leo -> row 2`, ...
  This sorted list (the index) maps keys back to table rows, enabling quick lookup without scanning the entire table.

![A stylized diagram showing a table of rows with names and cities on the left and, on the right, the same names sorted alphabetically in an index column with their original row numbers. The image illustrates how an alphabetical index maps back to the original table rows.](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Databases/How-Database-Indexing-Works/alphabetical-index-maps-to-rows.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=0fe2f2a59e3d525a94e3995d544c975b)

Why not just scan the sorted list linearly? Databases use B-tree structures (commonly B+ trees) to make searches logarithmic in cost.

How B-tree indexing speeds lookups

* A B-tree organizes the index into pages (blocks) grouped as leaf nodes and internal nodes.
* Each leaf holds many keys (e.g., hundreds in production). Internal nodes contain separator keys that direct the search to the correct leaf.
* Example block grouping (conceptual): \[Ava, Ben, Leo], \[Maya, Nina, Omar], \[Raj, Sara, Tom]. A top node with separator keys M and R routes the lookup:
  * Keys \< M → first block
  * Keys ≥ M and \< R → second block
  * Keys ≥ R → third block

To find "Nina", the database:

1. Reads the top node, compares against the separators (M, R).
2. Determines Nina is in the second block.
3. Reads that leaf block, finds Nina and the pointer to her full row.
4. Fetches the corresponding row from the table.

Instead of checking nine (or millions of) rows, the query performs a few node reads and one row fetch.

![A diagram of a B-tree lookup: a table of rows (names and cities) on the left with "Nina" highlighted and arrows pointing to a B-tree node diagram on the right showing numbered steps to locate the record.](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Databases/How-Database-Indexing-Works/btree-lookup-nina-table-steps.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=64ba52a4b0a408b88d97e90ddce060f4)

Real-world considerations

* Each index page typically holds hundreds of keys, and B-trees grow by adding internal levels when needed.
* With a large branching factor, a tree height of 3–4 levels can index millions of rows.
* Lookup cost scales with tree height (roughly logarithmic), not the number of rows: e.g., four node reads + one row read versus millions of checks.

Clustered vs. Nonclustered Indexes

| Index Type | What the leaf stores | Typical use case |
| - | - | - |
| Clustered index | Full table rows in sorted order | Primary key in some databases; physically orders the table |
| Nonclustered index | Key + pointer (rowid or primary key) | Secondary indexes mapping keys to row locations |

When an index is clustered, the table's physical layout changes because the rows themselves are stored in the index leaves. Otherwise, the index remains a separate structure that points back to the table.

Index maintenance and write overhead

* Indexes must be updated on inserts, updates, and deletes.
* Example: If a new user "Zara" signs up, the base table may append her row at the end, but the alphabetical index must insert "Zara" in sorted order.
* If the target leaf node is full, the database splits the leaf, updates parent separator keys, and possibly propagates splits upward. These operations add write cost and additional storage requirements.

Indexes significantly speed read queries but increase the cost of writes and storage. Add indexes selectively on columns you query frequently (WHERE, JOIN, ORDER BY) and monitor write-heavy workloads.

Quick examples and references

* Create a basic nonclustered index (SQL):

```sql theme={null}
CREATE INDEX idx_users_name ON users(name);
```

* Drop an index:

```sql theme={null}
DROP INDEX idx_users_name ON users;
```

Further reading:

* B-tree and B+ tree overview: [https://en.wikipedia.org/wiki/B-tree](https://en.wikipedia.org/wiki/B-tree)
* General indexing strategies: [https://www.postgresql.org/docs/current/indexes.html](https://www.postgresql.org/docs/current/indexes.html)
* When and how to choose indexes: [https://use-the-index-luke.com/](https://use-the-index-luke.com/)

A final visual reminder: indexes map search keys to row locations but may or may not change the table's physical order depending on whether they are clustered.

![A left-side table lists ten rows of names and cities. On the right is a B-tree diagram showing those names organized into leaf nodes with their row numbers, with "Zara" highlighted in pink.](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Databases/How-Database-Indexing-Works/btree-names-table-zara-pink.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=276915d92c3ef051dc28a5507142cc33)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/1ee75c71-d566-42df-8cc2-7aa8e79b0f04/lesson/2619d1dd-4987-42f0-8c5c-503bf9884a29)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.