System Design · Concept Library · Free article
What Is a Database Index, and How Does It Speed Up Queries?
Replace a growing table scan with a lookup structure designed around the query you need to serve.
A database index is a separate lookup structure that helps the engine find matching rows without scanning the whole table. A B-tree is the usual default because it supports equality, ranges, and ordered reads. The useful index follows the query: its filters, sort order, and returned columns. Every index also consumes storage and must be updated on writes, so confirm the chosen plan with EXPLAIN instead of indexing every column.
The query stays the same; the work does not
Hatch resolves x7Gk2 with one query: SELECT long_url FROM links WHERE code = $1. At a thousand rows, a scan can look fast enough. At ten million rows, that same plan may inspect page after page before it finds one match. The product slowed because the amount of work per request grew with the table.
An index keeps an ordered map from code values to row locations. The engine walks that smaller structure to narrow the search, then fetches the matching row. The request still asks the same question, but the plan stops reading unrelated data.
How does a B-tree index work?
A B-tree stores sorted keys in page-sized nodes. Each internal node points to many children, so the tree has a high branching factor and remains shallow as rows are added. Equality lookup follows one path. A range lookup finds its starting key, then walks adjacent leaf entries in order.
The database keeps the tree balanced as values are inserted and removed. That maintenance is part of the write cost, but it gives reads predictable navigation rather than a chain that grows with insertion order.
The interactive version of this example is available when JavaScript loads.
Walk a lookup down the tree and count the steps rather than the rows. The depth barely moves as the table grows, because each level multiplies the rows covered by the branching factor rather than adding to them, so a table ten times larger typically costs one more level and not ten times the work. That is the entire reason an index changes the shape of a query: a scan grows with the table and a descent grows with its logarithm.
When should you add an index?
Start from the query, not the column list. For WHERE user_id = ? ORDER BY created_at DESC, a multicolumn B-tree on (user_id, created_at DESC) can narrow to one user and already provide the requested order. PostgreSQL can use constraints on different columns, but a B-tree is normally most efficient when equality conditions constrain its leading columns.
Selectivity matters too. If a condition matches most rows, following many index pointers can cost more than reading the table once. The planner uses table statistics to choose. An ignored index is not automatically a defect.
| Query shape | Possible index | Why |
|---|---|---|
WHERE code = ? | UNIQUE (code) | Exact lookup and uniqueness enforcement |
WHERE user_id = ? ORDER BY created_at DESC | (user_id, created_at DESC) | Equality filter followed by ordered results |
WHERE status = 'open' AND customer_id = ? | Partial index on customer_id for open rows | Indexes only the subset this query needs |
WHERE lower(email) = ? | Expression index on lower(email) | Matches the expression used by the predicate |
A covering index may answer from the index alone
A normal PostgreSQL index scan finds candidate entries, then visits the table heap for row data and visibility checks. An index-only scan is possible when the index stores every column the query needs and the index type can return those values. PostgreSQL also consults its visibility map, so “covered” does not guarantee that every heap visit disappears.
Use included payload columns when a frequently run, mostly stable query earns the extra index size. A covering index is an optimization for a measured path, not a default schema rule.
How do you check whether an index is being used?
EXPLAIN shows the plan the optimizer chose. EXPLAIN ANALYZE runs the statement and adds actual timing and row counts, so use it with care on writes. A sequential scan can be correct for a small table or a query returning most rows. An index scan or index-only scan matters when it reduces the work for the real data distribution.
Compare estimated rows with actual rows. A large mismatch often points to stale or insufficient statistics. Run ANALYZE, inspect the predicate, and confirm that the index definition matches the query before adding another index.
What does an index cost?
An insert into links changes the table and every relevant index. Updates may do the same. Extra indexes consume storage, add write I/O, expand backup and cache pressure, and can lengthen maintenance. That is why the rule is not “index everything.” It is “index the queries that matter, measure the result, and remove indexes that do no useful work.”
A practical indexing loop
- Capture the slow query with realistic parameters and data volume.
- Run
EXPLAIN (ANALYZE, BUFFERS)in a safe environment and identify the expensive work. - Design the narrowest index that matches the filter and ordering.
- Run the plan again and compare rows, buffers, and elapsed time.
- Watch the write path and index usage after release; keep the index only if it earns its cost.
Primary references
- PostgreSQL: indexes
- PostgreSQL: multicolumn indexes
- PostgreSQL: index-only scans and covering indexes
- PostgreSQL: using EXPLAIN
Shape the shortcut around the query
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.