Skip to the page
Tecyfy

SQL interview question · medium

Explain the concept of indexing in databases. What are the trade-offs between having many indexes and few indexes?

The short answerAn index is a separate, sorted structure (usually a B-tree) that maps column values to the rows that contain them, so the database can find matching rows without reading the whole table.

The full answer

An index is a separate, sorted structure (usually a B-tree) that maps column values to the rows that contain them, so the database can find matching rows without reading the whole table. Each index speeds up the reads that can use it and slows down every write, because each INSERT, UPDATE and DELETE must update it too.

How it works Like the index at the back of a book: to find customer_id = 42, the database walks a small tree to the entries for 42 and follows them to the rows.

CREATE INDEX idx_orders_customer ON orders (customer_id);

Trade-offs

Many indexesFew indexes
ReadsMore queries find an index that fitsMore full scans
WritesSlower: every index is updatedFaster
Storage and memoryMore disk, and indexes compete for cacheLess
PlanningMore options for the optimizer, occasionally a wrong choiceSimpler
MaintenanceMore to monitor; unused indexes still cost writesLess

The right number depends on the workload: a reporting database that is loaded nightly can carry many indexes; a table taking thousands of inserts a second should carry few.

Kinds of index worth knowing

  • B-tree: the default; handles equality, ranges, sorting and prefix LIKE 'abc%'.
  • Composite (multicolumn): one index on (customer_id, order_date) serves filters on customer_id alone or on both, but not on order_date alone. Put equality columns first.
  • Covering: includes extra columns (INCLUDE in PostgreSQL and SQL Server) so the query never touches the table.
  • Partial or filtered: indexes only rows matching a condition, such as WHERE status = 'open', which keeps it small.
  • Hash: equality only.
  • Full-text, GIN and GiST (PostgreSQL) for text search, arrays, JSON and ranges.
  • Clustered: in SQL Server and MySQL InnoDB, the table itself is stored in the order of the clustered index (the primary key in InnoDB).

Good practice

  • Index for the queries you actually run: check plans with EXPLAIN.
  • Find unused indexes (pg_stat_user_indexes in PostgreSQL, sys.dm_db_index_usage_stats in SQL Server) and drop them.
  • Avoid indexing columns with very few distinct values on their own, such as a boolean, unless the index is partial.
  • Rebuild only when monitoring shows bloat or fragmentation hurts; routine rebuilds are rarely needed on modern systems.

Last updated 16 October 2026