Indexing
How database indexes work — B+ tree and hash indexes, clustered vs secondary, composite indexes and the leftmost-prefix rule, covering indexes, selectivity, and when indexes hurt.
Without an index, finding rows means a full table scan: reading every page. An index is an extra data structure, sorted by some columns, that lets the database jump straight to matching rows — like the index at the back of a book. Indexes are the single most important tool for database performance, and also the most commonly misused.
B+ tree indexes
The default index in nearly every relational database. Keys are kept sorted in a balanced tree whose leaves are linked together:
A B+ tree index supports:
- Equality:
WHERE email = 'ada@x.io' - Ranges:
WHERE created_at BETWEEN … AND …,>,< - Prefix matches:
WHERE name LIKE 'Ad%'(but notLIKE '%da') - Sorting:
ORDER BY created_atcan read the index in order and skip the sort - MIN/MAX in O(log n)
Cost: O(log n) page reads to find the first match (3–4 levels even for billions of rows), then sequential reads along the leaves.
Clustered vs secondary indexes
The table rows are stored in index order: the leaves are the rows. A table can have only one. InnoDB (MySQL) and SQL Server cluster on the primary key.
Leaves store the indexed columns plus a pointer to the row: a physical location (PostgreSQL's heap TID) or the primary key (InnoDB, requiring a second lookup in the clustered index).
That second lookup is why fetching many rows through a secondary index can be slower than scanning the table, and why the planner sometimes ignores your index.
Composite indexes and the leftmost-prefix rule
An index on (last_name, first_name, age) is sorted by last name, then first name within that, then age.
| Query filter | Can use the index? |
|---|---|
last_name = 'Smith' | ✓ |
last_name = 'Smith' AND first_name = 'Ann' | ✓ |
last_name = 'Smith' AND age = 30 | Partly: seeks on last_name, then filters on age |
first_name = 'Ann' | ✗ (not the leftmost column) — like looking up a first name in a phone book |
last_name > 'S' AND first_name = 'Ann' | Seeks on the range; first_name is filtered |
Covering indexes
If the index contains every column a query needs, the database never touches the table: an index-only scan.
-- Query: SELECT email, created_at FROM users WHERE status = 'active' ORDER BY created_at;
CREATE INDEX idx_users_status_created ON users (status, created_at) INCLUDE (email);Other index types
| Type | Good for | Examples |
|---|---|---|
| Hash | Equality only, O(1) | Postgres hash indexes, Memory engine, hash-partitioned KV stores |
| Partial | Indexing a subset: WHERE deleted_at IS NULL | PostgreSQL, SQLite (MySQL lacks them) |
| Expression | Indexing a computed value: lower(email) | PostgreSQL, MySQL 8 functional indexes |
| GIN / inverted | Contents of arrays, JSON documents, full-text search | Postgres GIN, Elasticsearch |
| GiST / R-tree | Geometric and range data, nearest neighbour | PostGIS |
| BRIN | Huge, naturally ordered tables (time series) — tiny index of block ranges | PostgreSQL |
| Bitmap | Low-cardinality columns in analytics | Oracle, column stores |
| Vector (HNSW, IVF) | Similarity search on embeddings | pgvector, FAISS (Embeddings & RAG) |
Selectivity: when indexes help
An index helps when a query selects a small fraction of rows. Rules of thumb:
- High-cardinality columns (email, user_id) → excellent.
- Low-cardinality columns (
is_active,countrywith 3 values) → usually useless alone; the planner prefers a scan. Combine them in a composite or partial index. - Returning more than ~5–20% of the table → a sequential scan is often faster than random index lookups.
Why isn't my index used?
| Cause | Example | Fix |
|---|---|---|
| Function on the column | WHERE lower(email) = …, WHERE date(created_at) = … | Expression index, or rewrite as a range |
| Type mismatch / implicit cast | Comparing a varchar column with a number | Match the types |
| Leading wildcard | LIKE '%smith' | Trigram/full-text index |
| Not the leftmost column | Index (a, b), filter on b | Add an index starting with b |
OR across columns | WHERE a = 1 OR b = 2 | Separate indexes (bitmap OR) or UNION |
| Low selectivity / stale statistics | Planner estimates many rows | ANALYZE; reconsider the index |
Always check with EXPLAIN ANALYZE (Query processing).
The cost of indexes
Indexes aren't free:
- Every write must update every index on the table. Ten indexes ≈ ten extra B-tree updates per insert.
- They use disk and, more importantly, buffer pool memory.
- Unused and duplicate indexes are pure overhead. (Postgres:
pg_stat_user_indexesshows usage.)
- B+ tree indexes support equality, ranges, prefix matches and ordered reads in O(log n).
- Clustered indexes store rows in key order; secondary indexes point to rows (an extra lookup).
- Composite indexes follow the leftmost-prefix rule: equality columns first, range/sort last.
- Covering indexes enable index-only scans.
- Index selective columns; functions, casts and leading wildcards defeat indexes.
- Every index slows writes and uses memory — keep only those that earn their keep.
QWhy not index every column?easy
Each index must be updated on every insert, update and delete, uses storage and buffer-pool memory, and gives the planner more choices to evaluate. Most single-column indexes on low-selectivity columns would never be used anyway.
QHow would you speed up a slow query?medium
Look at the plan with EXPLAIN ANALYZE; find sequential scans on large tables, bad row estimates, expensive sorts or nested loops over many rows. Add or adjust indexes (composite, covering, partial), rewrite non-sargable predicates, update statistics, fetch fewer columns and rows, and only then consider caching or denormalising.