Database index

On this page 7

A database index is an auxiliary data structure that maps the values of one or more columns to the locations of the rows that contain them, so the database engine can find matching rows without scanning the entire table. In databases, indexing is the primary tool for making selective queries fast, and nearly every relational and many non-relational systems depend on it.

An index is a redundant copy of selected data, organized for lookup rather than storage. That redundancy is the source of its central trade-off: reads become faster, while writes, storage and maintenance become more expensive. Designing indexes well means matching them to the queries an application actually runs.

How a database index locates rows

A database index works by keeping index keys in a searchable order or hashed layout, each paired with a pointer to a row, which is a row identifier, a physical address or a primary key value. Instead of reading every page of a table, the engine walks the index to the relevant keys and then fetches only the matching rows.

Most general-purpose indexes are balanced B-tree structures. Because each node holds hundreds of keys, a tree over hundreds of millions of rows is usually only three to five levels deep, so a single-row lookup needs just a handful of page reads. This logarithmic cost, written O(log n), is what turns a full scan into a near-instant search.

The final step matters for performance. After finding keys, the engine may need a heap or table lookup to retrieve columns that the index does not contain. When the index already holds every column a query needs, the engine can perform an index-only scan and skip the table entirely.

Main types of database indexes

Database indexes differ in their underlying structure and in the queries they accelerate, so the right type depends on the operators a workload uses. The table below summarizes the most common families that appear in modern engines such as PostgreSQL, MySQL, SQL Server and Oracle.

Index typeSupports wellTypical limitation
B-tree indexEquality, ranges, sorting, prefix matchesLess efficient for very low-cardinality columns
Hash indexExact equality lookupsNo range queries or ordering
Bitmap indexLow-cardinality columns in analyticsCostly under frequent concurrent updates
GIN indexArrays, JSON documents, full-text termsSlower to build and update
GiST and spatial indexesGeometric and nearest-neighbor searchesLossy matches need a recheck step
BRIN indexHuge tables with naturally ordered dataCoarse filtering only
Common index structures and their strengths

Beyond structure, indexes are classified by how they relate to table storage and which rows they cover. A clustered index determines the physical order of the table, while a non-clustered or secondary index is a separate structure pointing back to the rows.

VariantDefinitionCommon use
Clustered indexTable rows stored in index key orderPrimary keys, range-heavy access
Composite indexKey built from several columns in a fixed orderQueries filtering on multiple columns
Covering indexIncludes every column a query readsHot read paths that avoid table lookups
Unique indexRejects duplicate key valuesEnforcing business identifiers
Partial indexIndexes only rows matching a predicateActive records, unprocessed queue items
Expression indexIndexes a computed valueCase-insensitive search via lower(email)
Index variants by scope and behavior

Database index versus a sequential scan

An index is not always faster than reading the whole table, and the query planner decides between them using cost estimates. Its decision depends heavily on index selectivity, meaning the fraction of rows a condition returns, because each index match may cost a random page read.

Query characteristicLikely access pathReason
Returns a few rows of millionsIndex scanFew page reads replace a full scan
Returns a large share of the tableSequential scanSequential reads beat many random reads
Needs only indexed columnsIndex-only scanTable pages are not visited
Medium selectivity, scattered rowsBitmap index scanCollects matches, then reads pages in order
Small tableSequential scanWhole table fits in a few pages
How the planner typically chooses an access path

The crossover point varies by storage and engine, but on traditional disks an index often loses once a query returns more than a few percent of rows. On solid-state storage with cached data, the threshold is higher. Stale statistics are a frequent reason the planner picks the wrong path.

Designing effective indexes

Effective indexing starts from the real query workload, not from the schema alone. Engineers examine slow-query logs and execution plans, produced by commands such as EXPLAIN, and then index the columns used in WHERE, JOIN and ORDER BY clauses of the most frequent or most expensive statements.

  • Column order in composite indexes matters: an index on (customer_id, created_at) serves filters on customer_id alone, but not filters on created_at alone, a rule known as the leftmost prefix.
  • Put equality columns before range columns so the range condition can use the remaining ordered part of the key.
  • Avoid functions on indexed columns in predicates unless a matching expression index exists, because WHERE year(created_at) = 2025 usually prevents index use.
  • Index foreign keys that are used in joins or cascaded deletes to prevent full scans of child tables.
  • Remove unused and duplicate indexes, which cost writes and memory while giving nothing back.

Costs, limitations and common mistakes

Every index imposes write amplification: each INSERT, DELETE and many UPDATE statements must modify every affected index as well as the table. A table with ten indexes can make writes several times slower, which is why write-heavy systems keep indexes deliberately lean, and why some engines use LSM trees to absorb write load.

SymptomLikely causeRemedy
Slow filtered queriesMissing index on filter columnsAdd a targeted single or composite index
Index exists but is ignoredLow selectivity or function on columnRewrite predicate or add expression index
Slow inserts and updatesToo many or redundant indexesDrop unused indexes after monitoring
Growing index size over timeFragmentation or bloatSchedule an index rebuild or reindex
Plans change unexpectedlyOutdated table statisticsRefresh statistics regularly
Symptoms of poor indexing and their remedies

Indexes also consume memory in the buffer cache, and an index that no longer fits in memory loses much of its advantage. Finally, indexing does not fix poorly written queries or flawed data models; it is one part of performance tuning, alongside schema design, caching and query structure.

In everyday language

A database index works much like the index at the back of a thick reference book. You do not read every page to find a topic. You look up the word, see the page number and go straight to the right place.

There is a catch. The book index must be updated whenever pages change. It also makes the book a little thicker. Databases face the same deal: indexes make finding data fast but make changing data slower. So they are added only where searching really matters.

Seen in the real world

A regional logistics company stores shipment records in a PostgreSQL table that has grown to about 80 million rows. Its customer portal lets clients see their shipments from the past 30 days, and that page had started taking six to nine seconds to load because each request scanned a large part of the table.

A database engineer reviewed the execution plan and found a sequential scan filtering on client_id and sorting by shipped_at. She created a composite index on client and shipping date, in that order, and included the status column so the page query could be answered mostly from the index.

After the index was built during a low-traffic window, the same query completed in under 20 milliseconds. Write throughput for new shipments dropped by only a few percent, an acceptable cost, and the team added index usage monitoring to catch future regressions.