Skip to main content
Beginnerconceptual

What is indexing in a database, and when can an index make things slower?

ReportedSource: GeeksforGeeks interview experience: TCS Ninja + Digital

Quick answer

An index (usually a B+ tree) maps column values to rows so lookups avoid full scans (O(log n)). Costs: slower writes, storage, little benefit on low-selectivity columns; verify with EXPLAIN.

What an index is. A separate data structure (usually a B+ tree) that maps column values to row locations, like a book's index. A lookup on an indexed column goes from a full table scan, O(n), to roughly O(log n).

Types to name. Primary/clustered index (table rows stored in key order; one per table in many engines), secondary/non-clustered index (points to rows), unique index, composite index on several columns (column order matters: an index on (city, age) helps WHERE city = ? but not WHERE age = ? alone), hash index for equality lookups.

query.sql
CREATE INDEX idx_orders_customer ON orders(customer_id);

When indexes hurt.

  • Every INSERT/UPDATE/DELETE must also update the indexes: write-heavy tables slow down.
  • Extra storage.
  • Low-selectivity columns (e.g. gender) rarely help; the optimizer may ignore them.
  • Functions on the column (WHERE LOWER(email) = ...) can prevent index use unless you index the expression.

Rule of thumb. Index columns used in frequent WHERE, JOIN and ORDER BY clauses; check with EXPLAIN.

See the concept: Atomic publication

Atomic publication

BEGIN TRANSACTION;

  1. 1Close and insert customer versions
  2. 2Upsert orders, sales, payments
  3. 3Insert batch ledger row
  4. 4Advance watermark

COMMIT: batch published

Committed watermark

Moves forward only after COMMIT.

Everything inside BEGIN…COMMIT lands together or not at all. A failure leaves the old facts and the old watermark untouched.

Discussion