Serksa
All Concepts
API & Backend

Database Indexing

1

What is it?

<strong>Database indexing</strong> is creating a data structure that allows the database to find rows quickly without scanning the entire table. It's like a book indexβ€”instead of reading every page, you look up the page number.

2

Think of it like...

The Library Catalog Analogy

Without an index, finding a book means checking every shelf (slow). With a card catalog (index), you instantly know which shelf to check (fast).

πŸ“š

Books (Database Rows)

All your data

πŸ“‡

Card Catalog (Index)

Quick lookup

πŸ”

Search (Query)

Find what you need

3

Visual Flow

πŸ”Query

Find User by Email

β†’
πŸ“‡Index

Email Index

β†’
⚑Fast Lookup

O(log n) vs O(n)

4

Where you see it

1

Create index

CREATE INDEX idx_email ON users(email)

2

Database builds B-tree

Sorted structure for fast lookups

3

Query uses index

SELECT * FROM users WHERE email = 'john@example.com'

4

Fast lookup

Finds row in O(log n) instead of O(n)

5

Trade-off: Slower writes

Inserts/updates must update index too

5

Common Mistake

❌

Wrong

"Index every column for maximum speed"

βœ…

Correct

<strong>Indexes have trade-offs</strong>. They speed up reads but slow down writes and use disk space. Only index columns you frequently query or sort by.

πŸ’‘ Real-World Example

E-commerce product search:

1

Without index: Scan 1M products β†’ 2 seconds

2

With index on 'name': Find product β†’ 10ms (200x faster!)

3

Index on 'category', 'price' for filtering

4

Composite index on (category, price) for combined queries