What it is
A database index is an extra data structure that lets the database find rows by the value of some columns without reading the whole table. Like the index at the back of a book, it maps values (customer 6,042) to locations (these pages). The table stays as it is; the index is a separate, sorted copy of the indexed columns with pointers to the rows, kept up to date on every write.
Why it exists
Without an index, the only way to answer WHERE customer_id = 6042 is to read every row and check it: a full table scan. That is fine for a few thousand rows and hopeless for millions, and it gets worse as the table grows, even though the query and its result don't change. Indexes make lookup cost depend on the depth of a tree (a few page reads) instead of the size of the table.
How it works
B-trees. The default index in PostgreSQL, MySQL (InnoDB), SQL Server and Oracle is a B-tree (strictly a B+tree). Keys are stored in sorted order in fixed-size pages. Leaf pages hold the keys and row pointers (or, in a clustered index, the rows themselves). Above them, branch pages hold key ranges pointing to the pages below, up to a single root. Pages hold hundreds of keys, so three or four levels cover hundreds of millions of rows. A lookup reads one page per level; a range query (BETWEEN, ORDER BY ... LIMIT) finds the start and then walks the leaves in order.
The query planner. The database estimates the cost of each way to run a query (scan, index lookup, index range scan, bitmap scan) from statistics about the data, and picks the cheapest. An index existing doesn't mean it is used; EXPLAIN shows the chosen plan, EXPLAIN ANALYZE runs it and shows real times and row counts.
Selectivity. An index pays off when the filter matches a small fraction of rows. Each match found through the index may mean a random read of a table page; past a few percent of the table, reading the table sequentially is cheaper, and the planner says so.
Composite indexes. An index on (status, created_at) sorts by status, then by date within each status. It serves filters on status, and on status plus a range or sort on created_at, but not filters on created_at alone: the leftmost columns must be used. Put equality filters first, then the range or sort column. If the index also contains every column the query needs (a covering index, INCLUDE in PostgreSQL and SQL Server), the database doesn't touch the table at all.
Other kinds. Hash indexes (equality only), GIN/inverted indexes (full-text, arrays, JSON), GiST and R-trees (geometry, ranges), BRIN (huge append-only tables with naturally ordered columns), and partial indexes (WHERE status = 'pending') that index only the rows a query cares about.
When to use it
- Columns in
WHEREclauses of frequent queries, when the filter is selective. - Foreign keys used in joins (many databases don't index them automatically).
- Columns used in
ORDER BY ... LIMIT, combined with the filter columns in a composite index. - Uniqueness rules (
UNIQUEconstraints are enforced with an index).
When not to
- Low-selectivity columns on their own (booleans, a status with three values) unless combined with other columns or as a partial index.
- Small tables: a scan of a few pages is as fast as any lookup.
- Write-heavy tables with rarely-run queries: every index slows every insert; an occasional slow report may be the better deal.
- Speculatively: indexes "in case someone needs them" cost writes, disk, memory and backup time, and often go unused.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Adding an index | Selective reads become lookups instead of scans | Slower inserts/updates/deletes, disk and memory |
| Composite index | Serves filter + sort in one ordered read | Only helps queries using its leftmost columns; larger |
| Covering index | No table access at all for the query | Even larger index, more write cost |
| Many indexes | Many query shapes are fast | Every write maintains all of them; planner choices get harder |
| Partial index | Small index for exactly the rows queried | Only usable by queries with a matching condition |
Alternatives
- Caching results of hot, repeated queries (cache-aside) when the same answers are requested often.
- Denormalised or precomputed tables (materialised views, summary tables) for expensive aggregates an index can't make cheap.
- Search engines (Elasticsearch, OpenSearch) for full-text and faceted search across many fields.
- Partitioning very large tables by time or key, so queries touch only relevant partitions.
- Rewriting the query so it can use an existing index (avoid functions on indexed columns, leading wildcards, implicit type casts).
Failure modes
- Missing index discovered in production: a query that was fast on test data scans a table that has grown 1000×. Latency and database CPU climb until connections run out.
- Index not used: a function on the column (
WHERE lower(email) = ...), a type mismatch, a leading%wildcard or stale statistics make the planner ignore it. Check withEXPLAIN. - Write slowdown: each new index adds work to every insert; a busy write path can tip into saturation.
- Index build blocking writes: a plain
CREATE INDEXon a large table can lock it for a long time. Use online builds (CREATE INDEX CONCURRENTLY, online DDL). - Bloat: heavy updates and deletes leave index pages half empty, making lookups and scans of the index slower until it is rebuilt or vacuumed.
In production
Turn on the slow query log (or pg_stat_statements) and start from the queries that consume the most total time. Look at their plans with EXPLAIN ANALYZE, add indexes for selective filters and sorts, and confirm the plan changed. Build indexes online. Periodically list unused indexes (pg_stat_user_indexes, sys.dm_db_index_usage_stats) and drop them. Keep table statistics up to date so the planner's estimates are right.
Common misconceptions
- "An index makes every query on that column fast." Only selective ones. A filter matching a large share of rows is cheaper as a scan.
- "More indexes, more speed." Each index makes writes slower and takes memory; unused ones are pure cost.
- "Two single-column indexes are as good as one composite index." For filter + sort or multi-column filters, a composite index in the right column order is usually far better.
- "If the index exists, the database uses it." The planner decides. Check the plan.
Interview angle
When a design has a database, name the access patterns and the indexes that serve them ("orders by customer, newest first: composite index on customer_id, created_at"). Expect follow-ups: how a B-tree lookup works and why it is O(log n), why indexes slow writes, what selectivity means, why a low-cardinality column isn't a good index on its own, the leftmost-prefix rule for composite indexes, and how you'd find a missing index in production (slow query log, EXPLAIN). Mentioning that indexes are the first fix before replicas, caches or sharding shows good judgement.
Model assumptions
This simulation has no query planner, storage pages or real B-trees. Index effects are a cost model: the database's mean read time stands for the cost of the app's main query (120 ms for a full scan of 1M rows, 240 ms for 2M rows, about 4–5 ms for an index lookup) and its mean write time for one insert (5 ms for the row plus about 5 ms per index). The database has 10 connections; a query waiting more than one second for a connection fails. Service times are lognormal (cv 0.3) and arrivals random. The B-tree walk in step 4 is a scripted illustration: the root, branch and leaf pages are scenery, and the packets moving between them are drawn on a fixed schedule, not simulated. Real ratios between scans and lookups depend on caching, row size and hardware, and are often far larger than in this model. Numbers show behaviour and orders of magnitude only.