Docs For AI
Indexing

Database Indexing

Database index principles, types, and optimization strategies

Database Indexing

Indexes are data structures used to speed up data retrieval in databases. Proper use of indexes can improve query performance by orders of magnitude.

Why Indexing Matters

Without Index vs With Index

Query without index (Full Table Scan):
┌─────────────────────────────────────┐
│ Table: users (1,000,000 rows)       │
│ Query: WHERE email = 'john@...'     │
│ Operation: Scan all 1,000,000 rows  │
│ Time Complexity: O(n)               │
│ Estimated Time: 500ms - 2s          │
└─────────────────────────────────────┘

Query with index (Index Lookup):
┌─────────────────────────────────────┐
│ Table: users (1,000,000 rows)       │
│ Index: idx_users_email              │
│ Query: WHERE email = 'john@...'     │
│ Operation: B-Tree lookup            │
│ Time Complexity: O(log n)           │
│ Estimated Time: < 1ms               │
└─────────────────────────────────────┘

Query Cost Analysis

Data SizeFull Table Scan (O(n))B-Tree Index (O(log n))
1,0001,000 comparisons~10 comparisons
100,000100,000 comparisons~17 comparisons
10,000,00010,000,000 comparisons~24 comparisons

Index Fundamentals

What is an Index?

An index is an additional data structure that maintains ordered references pointing to actual data:

Index Structure (B-Tree on email):

                    [john@...]
                   /          \
         [alice@...]           [mike@...]
         /        \             /        \
    [adam@...]  [bob@...]  [kate@...]  [zoe@...]
         |          |          |           |
         ▼          ▼          ▼           ▼
    Row Pointer  Row Pointer  Row Pointer  Row Pointer

Index Trade-offs

BenefitsCosts
Speeds up SELECT queriesIncreases storage space
Speeds up JOIN operationsSlows down INSERT performance
Speeds up ORDER BYSlows down UPDATE performance
Supports unique constraintsSlows down DELETE performance

Rule of thumb: Read-heavy tables benefit from more indexes; write-heavy tables should have indexes added cautiously.

Topics

  • Index Types - Detailed explanation of B-Tree, Hash, GIN, GiST and other index types
  • Index Strategies - Advanced strategies: composite indexes, covering indexes, partial indexes

On this page