Indexing

An index is a second, sorted copy of part of a table that lets the database find rows without reading all of them. The right index turns a query from seconds into milliseconds; the wrong ones slow down every write, waste memory and are never used. This lesson explains how indexes work, how to choose them, and how to keep them healthy. Examples use PostgreSQL; the principles apply to every relational engine.

How Indexes Work

Without an index, finding rows that match a condition means a sequential scan: reading every page of the table. An index stores the indexed values in a structure that can be searched quickly, each entry pointing to the row it came from.

B-tree Indexes

The B-tree is the default index type in practically every relational engine. It is a balanced tree whose leaves hold keys in sorted order, so a lookup descends a few levels — typically three or four even for hundreds of millions of rows — and then reads neighboring entries. Because the keys are sorted, one B-tree serves equality (=), ranges (<, BETWEEN), prefix matches (LIKE 'abc%'), ORDER BY and min/max.

B-tree index structure from root and branch pages to sorted leaf pages pointing to heap TIDs

Figure: Balanced B-tree traversal from root to sorted leaf pages pointing to table heap rows.

-- B-tree is the default access method; "USING btree" may be omitted.
CREATE INDEX customer_order_customer_idx
    ON customer_order USING btree (customer_id);

Hash and Specialized Indexes

TypeGood forNotes
HashEquality only.Cannot serve ranges or sorting. In PostgreSQL crash-safe since version 10; rarely better than a B-tree in practice.
GINValues containing many elements: jsonb, arrays, full-text search.Fast lookups, slower updates.
GiST / SP-GiSTGeometric, range and nearest-neighbor queries.Used by PostGIS and range types.
BRINVery large tables where values follow physical order, such as append-only timestamps.Tiny on disk; only effective when data is naturally clustered.

Other engines use different names for similar ideas — Oracle has bitmap indexes for low-cardinality analytics, SQL Server has columnstore indexes — but the B-tree remains the workhorse everywhere.

Choosing What to Index

Index for the queries you actually run, not for the columns you have. Start from the slowest and most frequent statements (see Query Optimization) and design the index that serves them.

Selectivity

Selectivity is the fraction of rows a condition returns. An index pays off when the condition is selective: finding one customer among a million is ideal, while a status column where 95% of rows are 'shipped' is a poor index candidate for that value. When a condition matches a large share of the table, reading the table sequentially is cheaper than jumping between index and table, and the planner will rightly ignore the index.

Composite Indexes and Column Order

A multi-column index is sorted by its first column, then by the second within each first value, and so on — like a phone book sorted by surname, then first name. It can serve conditions on a leading prefix of its columns, but not on a later column alone:

CREATE INDEX customer_order_cust_date_idx
    ON customer_order (customer_id, ordered_at DESC);

-- Served well: equality on the first column, range/sort on the second.
SELECT id, ordered_at FROM customer_order
 WHERE customer_id = 42
 ORDER BY ordered_at DESC
 FETCH FIRST 10 ROWS ONLY;

-- Not served efficiently: the leading column is missing.
SELECT id FROM customer_order WHERE ordered_at >= DATE '2026-01-01';

A useful rule: put columns compared with equality first and the column used for ranges or sorting last. A composite index also makes a separate index on its leading column redundant.

Index Foreign Keys

PostgreSQL creates indexes for primary keys and unique constraints automatically, but not for foreign-key columns. Without one, joins from parent to child scan the child table, and every delete or key update on the parent must scan the child to check for references — often while holding locks. Index foreign-key columns by default unless the table is tiny.

Partial, Expression and Covering Indexes

An index does not have to contain every row or a plain column. Shaping it to the query makes it smaller and faster.

Partial Indexes

A partial index includes only rows that match a predicate. It is ideal when queries always target a small subset, such as unprocessed work:

-- Only open orders are indexed; the index stays small as history grows.
CREATE INDEX customer_order_open_idx
    ON customer_order (ordered_at)
 WHERE status = 'open';

Partial unique indexes also enforce conditional rules, such as “at most one active subscription per customer”.

Expression Indexes

If a query filters on an expression, an index on the plain column cannot be used. Index the expression itself, written exactly as queries write it:

CREATE INDEX customer_email_lower_idx ON customer (lower(email));

-- Uses the index: the expression matches the index definition.
SELECT id FROM customer WHERE lower(email) = lower('Ana@Example.org');

Covering Indexes and Index-Only Scans

When an index contains every column a query needs, the engine can answer from the index alone. PostgreSQL 11+ lets you add non-key payload columns with INCLUDE:

CREATE INDEX order_line_product_idx
    ON order_line (product_id) INCLUDE (quantity, unit_price);

In PostgreSQL, index-only scans also depend on the table's visibility map being current, which is maintained by VACUUM; on heavily updated tables they may still visit the table.

The Cost of Indexes

Every index is updated on every INSERT, on every DELETE, and on each UPDATE that changes an indexed column. Each index also takes disk space, competes for memory with table data, and lengthens backups and restores. An index that no query uses is pure overhead.

Find Unused and Duplicate Indexes

PostgreSQL counts index usage in pg_stat_user_indexes. Indexes with zero scans over a representative period (including month-end jobs) are removal candidates — except those that enforce uniqueness or a primary key:

SELECT s.relname        AS table_name,
       s.indexrelname   AS index_name,
       s.idx_scan       AS scans,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
  FROM pg_stat_user_indexes AS s
  JOIN pg_index            AS i ON i.indexrelid = s.indexrelid
 WHERE s.idx_scan = 0
   AND NOT i.indisunique
 ORDER BY pg_relation_size(s.indexrelid) DESC;

Statistics are per server: check every replica that serves reads before dropping an index, since a query may only run there.

Build and Maintain Indexes Online

A plain CREATE INDEX blocks writes to the table until it finishes. On a live system, build with CONCURRENTLY, which allows writes at the cost of a slower build that cannot run inside a transaction block. If it fails, it leaves an invalid index that must be dropped and retried.

CREATE INDEX CONCURRENTLY customer_order_status_idx ON customer_order (status);

-- Rebuild a bloated index without blocking writes (PostgreSQL 12+).
REINDEX INDEX CONCURRENTLY customer_order_status_idx;

-- Drop without blocking concurrent queries on the table.
DROP INDEX CONCURRENTLY customer_order_status_idx;

Indexes on frequently updated tables accumulate dead entries (bloat). Autovacuum reclaims space for reuse, but it does not shrink the file; periodic REINDEX CONCURRENTLY restores compact size where bloat is measured to be significant.

Practice Lab

Generate enough data for the planner to care: at least a few hundred thousand rows. In PostgreSQL, generate_series() creates test data quickly.

Design Indexes for Queries

  1. Create an orders table with a million rows spread across ten thousand customers and five statuses.
  2. Write three queries: one customer's recent orders, open orders older than a day, and a case-insensitive e-mail lookup.
  3. Run each with EXPLAIN ANALYZE, add one index per query (composite, partial, expression), and compare the plans and timings.

Audit an Existing Schema

  1. List every foreign-key column that has no index whose leading column matches it.
  2. Find indexes that are a leading prefix of another index on the same table.
  3. Measure the time of a bulk insert with and without three extra indexes, and record the write cost each index adds.