In short
A database index is a separate, ordered data structure that lets the engine locate matching rows without scanning the entire table, in the same way a book's index lets a reader avoid reading every page. Most relational databases build indexes as B-trees, which keep lookups, range scans and insertions all close to logarithmic time even as a table grows into millions of rows. Every index also has to be updated on every write, which means indexing is a genuine trade-off between read speed and write cost, not a free performance upgrade.
Without an index, finding a row that matches a condition requires a database to perform a full table scan: reading every row in the table and checking whether it matches. For a table of a few hundred rows this is unnoticeable. For a table of fifty million rows, a full scan can take seconds or minutes, and it gets slower in direct proportion to the table's size no matter how the query is phrased.
An index avoids this by maintaining a second, smaller, ordered structure that maps values in a column (or combination of columns) to the physical locations of the rows containing them. The database can then search that structure instead of the table itself, and jump straight to the matching rows.
The B-tree, the default choice
The vast majority of indexes in relational databases such as PostgreSQL, MySQL and SQL Server are B-trees, or more precisely B+trees, a self-balancing structure invented for exactly this purpose in the 1970s. A B-tree keeps its keys sorted and organises them into a shallow tree of nodes, each holding many keys, so that even a table of tens of millions of rows can typically be searched in three or four node reads rather than millions of row comparisons.
- Lookups, insertions and deletions all complete in logarithmic time relative to the number of rows, meaning the cost grows very slowly as the table grows.
- Because keys are stored in sorted order, B-trees support efficient range queries — WHERE age BETWEEN 30 AND 40 — not just exact-match lookups.
- The tree stays balanced automatically as rows are added or removed, so performance does not degrade as the table changes over time.
- Leaf nodes are typically linked together, letting the database scan a contiguous range of sorted values without walking back up the tree.
Hash indexes: a narrower tool
A hash index maps each key to a bucket via a hash function, giving constant-time lookups for exact-match equality queries — but it cannot support range queries or sorting, because a hash function deliberately scrambles the order of its inputs. Most databases therefore use hash indexes only in specific situations, such as certain in-memory table types, while defaulting to B-trees everywhere else because equality is only one of the query patterns applications actually need.
| Property | B-tree index | Hash index |
|---|---|---|
| Equality lookups (col = value) | Fast, logarithmic | Fast, near-constant time |
| Range queries (col BETWEEN) | Supported efficiently | Not supported |
| Sorted output without extra sort step | Yes | No |
| Typical default in relational databases | Yes | No, used selectively |
How the query planner decides whether to use an index
Having an index does not guarantee the database will use it. Every relational database includes a query planner that estimates the cost of several possible execution strategies and picks the cheapest one, using statistics it maintains about how values are distributed in each column. If a WHERE clause matches most of the table — say, a status column where 95% of rows are 'active' and the query asks for active rows — a full table scan can actually be cheaper than following an index, because random-access lookups for that many matching rows cost more than one sequential read of the whole table.
This is why the standard troubleshooting tool is the execution plan, produced with a command such as EXPLAIN or EXPLAIN ANALYZE. It shows which strategy the planner chose for a given query and reveals the actual difference between what was estimated and what happened at runtime, which is often the fastest way to discover a missing or unused index.
Composite indexes and column order
An index can span multiple columns, and the order those columns are listed in matters enormously. A composite index on (country, city) is sorted first by country and then by city within each country, so it efficiently serves queries filtering on country alone, or on country and city together — but it cannot efficiently serve a query filtering on city alone, because cities are not grouped together across the whole index; they are scattered within each country's section.
- Put the column used in equality filters first, since it narrows the search space most immediately.
- Put columns used in range filters after equality columns, because a range filter effectively stops the index from being useful for any column that comes after it.
- If a query only ever needs a subset of columns already in the index, some databases can answer entirely from the index without touching the table — a covering index.
- Avoid indexing columns with very low cardinality (few distinct values, such as a boolean flag) on their own, since the planner will often prefer a full scan anyway.
The write cost that indexes are not free from
Every index on a table must be updated whenever a row is inserted, deleted, or has an indexed column modified. A table with six indexes pays that maintenance cost six times over on every write, which is why indiscriminately indexing every column is a common and costly mistake. The trade-off is real: an index that speeds up a rarely-run report query but slows down a high-frequency write path can make the overall system slower, not faster.
Illustrative write latency by number of indexes on a table
Milliseconds per insert, illustrative figures for a mid-sized table
Figures are illustrative only, intended to show the shape of the relationship; actual overhead depends on index type, table size, hardware and concurrency.
Adding an index
Pros
- Can turn a query from a full table scan into a near-instant lookup, especially valuable as tables grow
- Range and sort operations become far cheaper when the relevant column is already stored in order
- A covering index can let some queries be answered without reading the underlying table at all
- Unique indexes double as a data-integrity constraint, preventing duplicate values outright
Cons
- Every write to the table must also update every index on it, adding latency to inserts, updates and deletes
- Indexes consume additional disk space, sometimes comparable to or larger than the table itself
- An unused or redundant index still incurs its full write cost with no compensating read benefit
- Composite index column order must match actual query patterns, or the index may go unused entirely
Key points
- An index is a separate, ordered structure that lets a database avoid scanning every row in a table.
- B-trees are the default index type because they support equality, range and sorted queries in logarithmic time.
- The query planner may ignore an index if a full scan is estimated to be cheaper, particularly for low-selectivity filters.
- Column order in a composite index must match the query's filter pattern, or later columns become ineffective.
- Every index adds write overhead, so indexing decisions should be driven by measured query patterns, not guesswork.
Other index structures worth knowing
B-trees and hash indexes cover most everyday needs, but several other structures exist for specialised query patterns. A GiST or GIN index, available in PostgreSQL, supports full-text search and geometric or range containment queries that a plain B-tree cannot express efficiently. A bitmap index, common in analytical and data-warehouse systems, represents each distinct value in a low-cardinality column as a compact bit array, which can be combined extremely quickly across several columns at query time — the opposite scenario from the low-cardinality warning given earlier for transactional B-tree indexes, because analytical workloads favour scanning large aggregates rather than pinpointing single rows.
Log-structured merge trees, or LSM-trees, are used by several write-optimised databases, including many NoSQL and time-series systems, because they turn random writes into sequential ones by first buffering changes in memory and periodically flushing sorted segments to disk. The trade-off is that reads sometimes need to check several of these segments before returning a result, which is the mirror image of the B-tree's read-optimised, write-costly design.
| Structure | Best suited to | Typical downside |
|---|---|---|
| B-tree | General-purpose equality, range and sort queries | Write cost grows with number of indexes |
| Hash index | Pure equality lookups | No range or sort support |
| GiST / GIN | Full-text search, geometric and containment queries | More complex to tune than a B-tree |
| Bitmap index | Low-cardinality columns in analytical queries | Poor fit for high-write transactional tables |
| LSM-tree | Very high write throughput workloads | Reads may need to check multiple segments |
Index maintenance and fragmentation
Over time, heavy insert and delete activity can leave a B-tree with partially empty pages, a condition generally called fragmentation, which slightly increases the number of page reads needed for a given query. Most production databases provide a maintenance operation — variously called reindexing, rebuilding, or vacuuming depending on the engine — that compacts the structure back down. How often this is worth running depends heavily on write volume and is usually informed by monitoring index bloat rather than done on a fixed schedule.
Sponsored video
AdvertisementChecking for a video ad…
Frequently asked questions
Sources
- PostgreSQL Documentation: Indexes — PostgreSQL Global Development Group
- MySQL 8.0 Reference Manual: Optimization and Indexes — Oracle Corporation
- Using EXPLAIN — PostgreSQL Global Development Group
- Use the Index, Luke: a guide to database performance — Markus Winand, independent database performance reference
About the author
Michael Adeyemi — Senior Technology Writer
Michael writes Inquro's computing and web-infrastructure coverage. He worked for eight years as a platform engineer on high-traffic content systems before moving into full-time technical explanation, and he still prototypes every measurement described in his articles before publishing the numbers.
- Qualifications
- MSc, Distributed Systems — University of Manchester
- BEng, Computer Engineering — University of Lagos
- Experience
- Eight years as a platform engineer on high-traffic content delivery systems
- Four years writing standards-based technical documentation
- Subject areas:
- Web performance, Networking, Systems architecture
- Contact:
- michael@inquro.example
Reviewed for factual accuracy by Dr. Luca Marchetti, Science Editor (PhD, Environmental Physics), on 11 December 2025.
Traceability of every figure to a named dataset, correct handling of uncertainty, and whether a finding is being generalised beyond its study design.
Inquro articles are commissioned, sourced, reviewed and re-checked under a published editorial policy. Corrections are made in place and dated — write to editorial@inquro.example if you find an error.






