8. Indexing: when, where, which type, and what goes wrong
Indexes are the most powerful tuning tool you have, and the easiest to overuse. Every index speeds up some reads and slows down every write to its table. Good indexing is a budget, not a reflex.
8.1When an index helps, and when it doesn't
An index helps when:
- A query reads a small fraction of a large table through a selective predicate.
- It supports the inner side of a nested loop join (the join column of the table being looked up).
- It delivers rows already in the order a query needs for
ORDER BY,GROUP BYor a merge join, avoiding a sort. - It covers a hot query completely, so the table itself is never touched.
- It enforces uniqueness, or supports a foreign key (Chapter 7).
An index doesn't help, or costs more than it saves, when:
- The predicate matches a large share of the table. Past a break-even point, often in the low single-digit percent of rows, a full scan is cheaper than millions of individual lookups. Where exactly that point lies depends on how well the table's physical order matches the index, which statistics such as Oracle's clustering factor and PostgreSQL's correlation measure.
- The table is small enough to scan in a few pages.
- The table is write-heavy and the index serves a rare query.
- The query wraps the column in a function or converts its type (Chapter 7), unless you index the expression itself.
8.2Where: designing composite indexes
Column order is the most important decision in a composite index. A dependable rule for a given query:
- Columns compared with equality (
=,INwith few values) first. - Then one range column (
<,>,BETWEEN,LIKE 'abc%'). Columns after a range column can't narrow the search further, though they can still filter or cover. - Then columns used for ordering, when they follow the equality columns, so the sort disappears.
- Then columns needed only to cover the query, or put them in an
INCLUDEclause where the engine supports it.
-- The query
SELECT order_id, total_amount
FROM orders
WHERE customer_id = :c AND status = 'OPEN' AND order_date >= :since
ORDER BY order_date;
-- An index that finds the rows, returns them in order, and covers the query
CREATE INDEX ix_orders_cust_status_date
ON orders (customer_id, status, order_date) INCLUDE (total_amount);- The leftmost prefix rule. An index on
(a, b, c)serves predicates ona, ona, b, and ona, b, c, but not onbalone. Some optimizers can skip scan past a leading column with few distinct values; treat that as a bonus, not a design. - "Most selective column first" is a myth as a universal rule. For a single query with several equality predicates, their order matters little. What matters is which column order lets the same index serve the most important queries.
8.3Index types and where each fits
| Type | Best for | Engines | Watch out for |
|---|---|---|---|
| B-tree | Equality, ranges, sorting: the default for almost everything | All | Nothing special; it's the baseline |
| Bitmap | Low-cardinality columns in read-mostly warehouses, combining many predicates | Oracle Enterprise Edition | Never on tables with concurrent DML: one bitmap entry covers many rows, so locks collide |
| Function-based or expression | Queries that filter on an expression such as UPPER(email) | Oracle; PostgreSQL; SQL Server via an indexed computed column; MySQL 8.0.13+ functional key parts | The query must use exactly the indexed expression |
| Partial or filtered | A small, hot subset of rows (status = 'OPEN') | PostgreSQL partial indexes; SQL Server filtered indexes | The query predicate must match the filter; in SQL Server, parameterized predicates often can't use a filtered index |
Covering (INCLUDE) | Hot queries that would otherwise look up the table for a few columns | SQL Server; PostgreSQL 11+ | Wider indexes cost more on every write |
| Clustered or index-organized | Range access by key; primary key lookups | SQL Server clustered indexes; InnoDB (always clustered by primary key); Oracle index-organized tables | Random keys (UUIDv4) cause page splits and poor cache locality; ever-increasing keys can cause last-page insert contention at very high concurrency (SQL Server 2019 adds OPTIMIZE_FOR_SEQUENTIAL_KEY) |
| Hash | Equality only | PostgreSQL (crash-safe since 10); SQL Server memory-optimized tables | No ranges and no ordering |
| GIN | JSONB, arrays, full text, trigram searches for LIKE '%x%' | PostgreSQL | Slower writes and larger size |
| GiST and SP-GiST | Geometric data, ranges, nearest-neighbor searches, exclusion constraints | PostgreSQL | Choose the operator class carefully |
| BRIN | Very large tables whose physical order follows a column, such as time | PostgreSQL | Useless when the physical order doesn't correlate with the column |
| Columnstore | Analytics over many rows: aggregates, scans, batch mode | SQL Server (clustered and nonclustered columnstore); Oracle Database In-Memory (a separately licensed option; 19c's Base Level allows up to 16 GB without it) | Not for single-row lookups; trickle inserts land in row-based delta stores first |
| Full-text | Word and phrase search | Oracle Text; SQL Server Full-Text Search; MySQL FULLTEXT; PostgreSQL tsvector with GIN | Word semantics, language rules and update latency |
| Reverse key | Spreading sequential inserts across blocks on Oracle RAC | Oracle | Range scans on the key become impossible |
8.4Finding index candidates
Every engine can point you at candidates: tables read mostly by full scans, the statements behind those scans, and in some engines the optimizer's own suggestions. Treat all of them as leads to investigate, not as indexes to create.
Test new indexes safely. Where the engine supports invisible indexes, create the index invisible first. It is maintained but ignored by the optimizer unless a session asks for it, so you can test it without changing anyone else's plans.
8.5Finding unused and duplicate indexes
Unused indexes still cost writes, memory, storage, backup time and replication bandwidth.
Duplicates. An index on (a) is usually redundant when (a, b) exists, unless it is unique, much narrower for a very hot query, or supports a foreign key on its own.
8.6Build and maintain indexes without hurting production
Building an index on a busy table can block writes for as long as the build runs, unless you build it online. Every engine has an online option, but the edition rules and the failure behavior differ.
Rebuilding indexes on a schedule because of "fragmentation" is mostly wasted work on modern SSD and SAN storage, and it generates large amounts of log. Rebuild for a reason, such as wasted space after heavy deletes or a measurable gain in reads:
8.7Common indexing pitfalls
- Over-indexing write-heavy tables: every index adds work, log and memory to each write.
- Overlapping indexes such as
(a),(a, b)and(a, b, c)on the same table. - The right columns in the wrong order, or a low-cardinality flag indexed on its own.
- Functions and implicit conversions that make the index invisible to the query.
- Unindexed foreign keys.
- Random keys (UUIDv4) as the clustered key; prefer a sequential key or UUIDv7.
- Creating every missing-index suggestion as-is.
- Index hints that outlive the reason they were added.
This is one chapter of the free database tuning guide for PostgreSQL, MySQL, SQL Server and Oracle. Download the whole guide as a PDF.