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.

Intermediate 5 min readLesson 7 of 14 Interview Q&A

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 CD E GH J K[ D | H ]M N PR S TV X Z[ R | V ][ M ]
Leaves hold keys plus pointers to rows, linked left to right for range scans.

A B+ tree index supports:

  • Equality: WHERE email = 'ada@x.io'
  • Ranges: WHERE created_at BETWEEN … AND …, >, <
  • Prefix matches: WHERE name LIKE 'Ad%' (but not LIKE '%da')
  • Sorting: ORDER BY created_at can 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

Clustered (primary) index

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.

Secondary (non-clustered) index

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 filterCan use the index?
last_name = 'Smith'✓
last_name = 'Smith' AND first_name = 'Ann'✓
last_name = 'Smith' AND age = 30Partly: 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.

SQL
-- 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

TypeGood forExamples
HashEquality only, O(1)Postgres hash indexes, Memory engine, hash-partitioned KV stores
PartialIndexing a subset: WHERE deleted_at IS NULLPostgreSQL, SQLite (MySQL lacks them)
ExpressionIndexing a computed value: lower(email)PostgreSQL, MySQL 8 functional indexes
GIN / invertedContents of arrays, JSON documents, full-text searchPostgres GIN, Elasticsearch
GiST / R-treeGeometric and range data, nearest neighbourPostGIS
BRINHuge, naturally ordered tables (time series) — tiny index of block rangesPostgreSQL
BitmapLow-cardinality columns in analyticsOracle, column stores
Vector (HNSW, IVF)Similarity search on embeddingspgvector, 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, country with 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?

CauseExampleFix
Function on the columnWHERE lower(email) = …, WHERE date(created_at) = …Expression index, or rewrite as a range
Type mismatch / implicit castComparing a varchar column with a numberMatch the types
Leading wildcardLIKE '%smith'Trigram/full-text index
Not the leftmost columnIndex (a, b), filter on bAdd an index starting with b
OR across columnsWHERE a = 1 OR b = 2Separate indexes (bitmap OR) or UNION
Low selectivity / stale statisticsPlanner estimates many rowsANALYZE; 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_indexes shows usage.)
Key takeaways
  • 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.
Interview questions
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.