Secondary index

On this page 7

A secondary index is an additional index built on columns other than the primary key that lets a database find rows by those columns without scanning the whole table. In databases and indexing, it complements the primary access path: the table is stored or identified by its primary key, while each secondary index offers another sorted route to the same rows, for example by email address, customer number or order date.

Every secondary index is a trade-off between read speed and write cost. It can turn a full table scan into a lookup of a few pages, but each insert, update and delete must also maintain every affected index, and each index consumes storage and memory.

How a secondary index locates rows

A secondary index stores pairs of index keys and row locators, usually in a B-tree sorted by the indexed columns. When a query filters on those columns, the engine descends the tree to the matching keys and then uses the locators to fetch the full rows. This second step is often called a lookup back to the table or a bookmark lookup.

What the locator contains depends on the storage engine. The difference has real performance consequences, because it decides how expensive each fetch is and what happens when rows move.

Storage designLocator in the secondary indexConsequence
Clustered table (InnoDB, SQL Server)Primary key valueExtra traversal of the clustered index per row
Heap table (PostgreSQL)Physical tuple identifierDirect page access, but row versions add entries
Heap table (Oracle)ROWIDFast fetch, rebuild needed after some moves
LSM-based storePrimary key valueLookup in the main tree, possibly several levels
Row locators used by common storage designs

In clustered designs, a wide primary key makes every secondary index larger, because the key is copied into each entry. That is one reason short integer or compact surrogate keys are often recommended.

Secondary index compared with other index types

The term secondary index describes the role of an index, not its data structure. In practice it overlaps strongly with the non-clustered index, while the primary or clustered index defines how the table itself is organized. The following comparison shows how the related concepts relate.

ConceptDefines row orderTypical number per table
Primary indexYes, in clustered enginesExactly one
Clustered indexYesAt most one
Secondary indexNoZero to many
Unique indexNo, unless clusteredAs many as needed
Covering indexNoSelected hot queries only
Secondary index and neighboring concepts

A secondary index can also be unique, composite, partial or expression-based. These properties are orthogonal: a composite partial secondary index on two columns with a filter condition is perfectly valid, and its usefulness depends on whether queries match its leading columns and predicate.

When the query planner uses a secondary index

The query planner chooses a secondary index only when it estimates that the index is cheaper than a sequential scan. The decisive factor is index selectivity: the smaller the fraction of rows a predicate matches, the more attractive the index. Each matching row may require a random page read, so beyond a certain fraction a full scan becomes faster.

The break-even point varies with storage, caching and how well the table is physically ordered by the indexed column, but it is often somewhere between 5 and 20 percent of rows on spinning disks and higher on fast SSD storage.

SituationLikely planReason
Equality on a highly selective columnIndex scanFew rows, few random reads
All needed columns are in the indexIndex-only scanNo table access needed
Moderate selectivity, many rowsBitmap index scanSorts locators to read pages in order
Predicate matches most rowsSequential scanRandom lookups cost more than reading everything
Function applied to the columnSequential scanPlain index does not match the expression
Typical access paths chosen for a secondary index

Planner decisions rely on up-to-date statistics. Stale histograms can lead the planner to ignore a useful secondary index or to use one that returns far more rows than estimated.

Designing secondary indexes well

Good secondary indexes are driven by real query patterns, not by a habit of indexing every column. Designers usually start from the slowest and most frequent queries, then add the smallest set of indexes that serves them.

  • Index foreign key columns used in joins and in cascading deletes.
  • Put equality columns before range columns in a composite index.
  • Add included columns to create a covering index for very hot queries.
  • Use a partial index when queries target a small, well-defined subset of rows.
  • Remove indexes that monitoring shows are never or rarely used.

In distributed and NoSQL systems, secondary indexes raise an additional question: whether the index is local to each partition or global across partitions. Local indexes are cheap to maintain but require querying every partition, while global indexes allow targeted reads but are often updated asynchronously, which can return slightly stale results.

Costs and common mistakes

Each secondary index adds write amplification: one logical insert becomes several physical writes, one per index plus logging. Tables with many indexes can show sharply lower insert throughput, larger backups and longer maintenance windows. The table below summarizes frequent problems.

SymptomCauseFix
Slow inserts and updatesToo many secondary indexesDrop unused or redundant indexes
Index exists but is ignoredLow selectivity or stale statisticsRefresh statistics or reconsider the index
Duplicate coverageIndex on (a) next to index on (a, b)Keep the composite index only
Growing index sizeBloat from updates and deletesSchedule an index rebuild
Query on lower(email) is slowFunction hides the columnCreate an expression index
Secondary index problems and fixes

A frequent misconception is that more indexes always mean faster queries. Beyond the queries they serve, extra secondary indexes only consume memory that the buffer cache could use for hot data, so every index should justify its maintenance cost.

A non-technical view

Imagine a large library where books stand on the shelves in order of their catalog number. That order is useful for staff, but visitors usually search by author or title.

A secondary index is like an extra card catalog sorted by author. Each card tells you where the book stands, so you can go straight to it instead of walking past every shelf. A library can keep several such catalogs, but every new book means updating every catalog, which takes time and space. That is the core balance: faster searching in exchange for more upkeep.

A concrete example

An online retailer stores about 40 million orders in a table whose primary key is the order identifier. Customer service agents constantly look up orders by customer email, and each search triggers a full scan that takes roughly 12 seconds during business hours.

The database team adds a secondary index on the customer email column and includes the order date and status as extra columns. After the change, the planner chooses an index-only scan for the agents’ summary screen and an index scan for detailed views, and typical lookups finish in under 10 milliseconds.

Monitoring shows that nightly order imports now run about 6 percent longer because of the additional index maintenance. The team accepts that cost, since the daytime gain for hundreds of agents far outweighs a slightly longer batch job.