TechnicalMedium SQL & Databases

What is a database index and what are its trade-offs?

Asked for Backend Developer, Full-Stack Developer

Why they ask this: Indexes are the first tool for slow queries; this checks real-world database thinking.

Answer

An index is a separate data structure (usually a B-tree) that lets the database find rows without scanning the whole table, much like the index at the back of a book.

Benefits: much faster WHERE, JOIN, ORDER BY and lookups on the indexed columns.

Trade-offs:

  • Writes (INSERT, UPDATE, DELETE) get slower because every index must be updated too.
  • Indexes use extra disk space and memory.
  • Indexes on columns with few distinct values (such as a boolean) rarely help on their own.

Composite indexes follow the leftmost-prefix rule: an index on (status, created_at) helps WHERE status = ? and WHERE status = ? ORDER BY created_at, but not WHERE created_at > ? alone.

sql
CREATE INDEX jobs_status_created_at_index ON jobs (status, created_at);
EXPLAIN SELECT * FROM jobs WHERE status = 'open' ORDER BY created_at DESC;

Use EXPLAIN to check whether a query actually uses an index.

Can you explain this in your own words?

Back to question bank