Database Indexes: Read/Write Trade-offs and Query Tuning
System DesignModel answerLast updated
Explain how relational indexes work, why they help reads but hurt writes, and walk through a systematic process for diagnosing and fixing a slow SQL query.
Database Indexes and Query Performance Tuning
Relational databases are central to most production systems, and understanding how they store and retrieve data efficiently is a core engineering skill. This question tests two related ideas: how indexes work under the hood, and how to methodically diagnose a query that is running far too slowly.
Where a concrete example helps, assume a table like:
trades(trade_id, product, trade_time, quantity, price)
Before You Answer
Consider what you would want to clarify in a real setting:
- Which database engine are we talking about (PostgreSQL, MySQL, SQL Server, a columnar warehouse like Redshift)? Tooling and index types vary.
- Is the slow query a transactional point-lookup or an analytical scan over millions of rows?
- Did it get slow recently, or has it always been this way?
- Can the schema and indexes be changed, or is the query text the only lever?
Part 1 — How Indexes Work
Answer the following questions about relational indexes:
- What is an index, and how is it physically structured?
- Why does having an index make certain queries faster?
- Why would you not put an index on every column?
- What is the impact of indexes on write operations?
Your answer should cover the data structure a typical index uses, the kinds of queries it helps (and those it does not), and the concrete costs — storage, write overhead, maintenance — that make blanket indexing a bad idea.
Part 2 — Diagnosing a Slow Query
You inherit a complex SQL query that runs in production and takes an unacceptably long time. Walk through how you would troubleshoot and tune it.
Your answer should describe:
- Where you start and what information you gather first
- What the execution plan tells you and how to read it
- The most common root causes and a concrete fix for each
- How you know whether your change actually helped
- What risks to watch for when applying a fix in production
Hints
Hint 1
Start with what a B-tree looks like on disk — an index is essentially a sorted copy of one or more columns with pointers back to the full rows. That structure explains both why range scans are fast and why updates are expensive.
Hint 2
For Part 2, resist the urge to list tips. Instead, describe a process: measure first (EXPLAIN ANALYZE), form a hypothesis about the bottleneck, make one change, measure again. The order matters.
Hint 3
Think about the asymmetry between reads and writes: an index turns an O(n) table scan into an O(log n) lookup for reads, but every INSERT, UPDATE, or DELETE now has to update the index tree as well as the table — that cost multiplies with the number of indexes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — How Indexes Work
Physical structure
The default index type in every major relational database (PostgreSQL, MySQL, SQL Server) is a B-tree: a self-balancing tree where leaf nodes hold the indexed column values in sorted order, each paired with a pointer (a row ID or primary key) that the engine follows to fetch the full row. Because values are sorted, the engine can binary-search for an exact match in O(log n) steps, or scan a contiguous range without touching the rest of the table.
A composite index — say, (product, trade_time) — is sorted by the first column first, then the second within each first-column value. That order matters: a query filtering only on trade_time cannot use this index efficiently, because the matching rows are scattered across the entire tree.
Other index types exist for specific workloads: hash indexes for exact-equality-only lookups, GIN/GiST indexes in PostgreSQL for full-text or geometric data, and columnar storage in analytical warehouses — but B-tree is the right default to discuss unless told otherwise.
Why indexes speed up reads
Without an index, the engine must read every row in the table (a full sequential scan, O(n)) to find matches. With a B-tree index on product, a query like WHERE product = 'WTI Crude' becomes an O(log n) tree traversal followed by a short range read of matching leaf entries, then a small set of row lookups. On a table with ten million rows the difference can be seconds vs. milliseconds.
Indexes also let the planner satisfy ORDER BY without a sort step, and can answer some queries entirely from the index without touching the table at all (a covering index).
Why not index everything
Every index is a separate data structure that must stay in sync with the table. The costs are:
- Write amplification. An
INSERTintotradesmust write the new row and update every index on that table. With ten indexes, a single row write becomes ten additional B-tree insertions. The same applies toUPDATE(for any indexed column that changes) andDELETE. - Storage. Each index is roughly proportional in size to the table. On a large table, a handful of indexes can consume more disk than the table itself.
- Planner overhead. More candidate indexes means the query planner spends more time choosing between them, and can occasionally pick the wrong one.
- Low-selectivity indexes are often useless anyway. An index on a boolean
is_cancelledcolumn where 95% of rows arefalsegives the planner little reason to use it — a full scan is cheaper when most of the table needs to be read regardless.
The practical rule: index columns that appear in WHERE, JOIN ON, or ORDER BY clauses in frequent, selective queries; audit and drop indexes that have not been used recently (PostgreSQL exposes this in pg_stat_user_indexes).
Part 2 — Tuning a Slow Query
Step 1: Get the execution plan with actual numbers
Run EXPLAIN ANALYZE (PostgreSQL) or the equivalent (SET STATISTICS IO ON in SQL Server, EXPLAIN FORMAT=JSON in MySQL). The key is to see actual row counts alongside estimated row counts. A large discrepancy — the planner expected 100 rows, got 2 million — is almost always the root cause, not the symptom.
Look for:
- Sequential scans on large tables where a selective index scan was expected
- Nested loop joins where one side returns many rows (O(n²) behavior)
- High actual rows vs. estimated rows indicating stale or missing statistics
- Sort steps that spill to disk
- Repeated subquery or function calls
Step 2: Fix the most expensive node first
Common causes and their fixes:
| Root cause | Fix |
|---|---|
| Missing index on a high-selectivity filter | Add the index; consider a covering index if the query reads only a few columns |
| Stale statistics causing bad row estimates | ANALYZE trades (Postgres) or UPDATE STATISTICS (SQL Server) |
| Implicit type cast blocking index use | WHERE trade_time = '2024-01-01' works if trade_time is a timestamp; casting the column (WHERE CAST(trade_time AS DATE) = ...) prevents index use — rewrite to avoid it |
| Inefficient correlated subquery | Rewrite as a JOIN or use a window function |
| Large intermediate result from a broad join | Push filters down before the join; filter early, join late |
| Partition pruning not happening | Check that the WHERE clause uses the partition key with no function wrapping it |
Step 3: Verify the change
After each change, re-run EXPLAIN ANALYZE and compare the actual execution time and node costs. Do not rely on elapsed wall time alone — cache effects make single-run timings noisy. Run the query several times and compare medians, ideally on a staging environment with production-representative data volume.
Check for side effects: a new index that speeds up this query may slow down a high-throughput INSERT elsewhere. Review what other queries touch the same table.
Common mistakes to avoid
- Tuning against a small development dataset and finding the result does not transfer to production scale.
- Adding many indexes speculatively without measuring which one the planner actually chooses.
- Modifying the live database (e.g.,
REINDEX,ALTER TABLE) without understanding locking implications — some operations take an exclusive lock and block all reads and writes. - Stopping after the first improvement found, rather than checking whether a second bottleneck is now the new limiting factor.
Rough priority order
- Update statistics (cheap, often immediately effective)
- Rewrite the query to remove anti-patterns (no schema change needed)
- Add or adjust indexes (low risk, high impact)
- Consider schema changes — partitioning, denormalization, materialized views (higher effort, reserved for when indexes alone are insufficient)