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.

- 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.
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 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
- Reads the top node, compares against the separators (M, R).
- Determines Nina is in the second block.
- Reads that leaf block, finds Nina and the pointer to her full row.
- Fetches the corresponding row from the table.

- 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.
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.
- Create a basic nonclustered index (SQL):
- Drop an index:
- B-tree and B+ tree overview: https://en.wikipedia.org/wiki/B-tree
- General indexing strategies: https://www.postgresql.org/docs/current/indexes.html
- When and how to choose indexes: https://use-the-index-luke.com/
