What is indexing in a database, and when can an index make things slower?
ReportedSource: GeeksforGeeks interview experience: TCS Ninja + Digital
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.
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
BEGIN TRANSACTION;
- 1Close and insert customer versions
- 2Upsert orders, sales, payments
- 3Insert batch ledger row
- 4Advance watermark
COMMIT: batch published
Committed watermark
Moves forward only after COMMIT.