Database Indexing
A database optimization that maintains sorted auxiliary data structures (typically B-Trees) to locate rows in O(log N) time instead of performing full table scans
Table of Contents
Structure Diagram
What is Database Indexing?
A database optimization that maintains sorted auxiliary data structures (typically B-Trees) to locate rows in O(log N) time instead of performing full table scans. It is a core concept in Databases & Caching within Web Dev.
Core Principles
Like the index at the back of a textbook, a database index maintains a sorted auxiliary structure—most commonly a B-Tree—mapping column values to row locations. Instead of scanning millions of rows sequentially (Full Table Scan, O(N)), the engine traverses 3–4 tree levels (O(log N)) to pinpoint matching records.
Indexes trade write speed and storage for read speed: every INSERT, UPDATE, or DELETE must also maintain every index defined on the table.
Practical Takeaways
- Order composite index columns carefully: Follow the leftmost prefix rule—place equality (
=) filter columns first, then range (>,BETWEEN) orORDER BYcolumns last (e.g.,(tenant_id, status, created_at)). - Keep predicates SARGable: Wrapping an indexed column in a function (
WHERE LOWER(email) = ...) prevents standard index usage. Transform the comparison value instead or create a functional/expression index. - Verify with
EXPLAIN ANALYZE: Never guess—confirm that the planner actually choosesIndex ScanorIndex Only Scan(covering index), and prune unused indexes that slow down writes.
Notable Examples
- Foreign key indexing in PostgreSQL: Explicitly indexing FK columns (which Postgres doesn't auto-index) to keep
JOINs andON DELETE CASCADEfast. - Covering indexes (
INCLUDE): Serving hot dashboard queries straight from the index without touching the main table heap.