NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Middle+2 views

What do you know about indexes? How can you determine which indexes are used in a query, and how can you tell which indexes are unnecessary or missing?

Practice

Asked at

AI answer

An index is a data structure that helps a DBMS find rows more quickly, but it takes up space and slows down write operations. B-tree indexes are the most commonly used; unique, composite, and specialized indexes—such as full-text indexes—are also available.

To understand what a query uses, examine its execution plan:

EXPLAIN SELECT ...;
-- In DBMSs that support it, use EXPLAIN ANALYZE for actual metrics.

The plan shows which index was selected, the access type, the estimated number of rows, filters, and the cost of operations. A slow query log and DBMS-specific statistics tools are useful for finding problematic queries. The plan should be checked against real workloads and data: estimates may be inaccurate, and the plan may change.

A missing index can be suspected when frequent slow queries filter, join, or sort by the same columns. For a composite index, the column order and the leftmost prefix used by the query matter; choose the order based on filters, sorting, and selectivity. After adding an index, verify it using the execution plan and measurements.

Unused indexes and redundant indexes may be unnecessary—for example, indexes that repeat the same set of columns or its prefix. However, low selectivity alone does not always make an index useless. Remove an index only after checking usage statistics and its impact on queries: doing so may hurt other use cases.