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?
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.
Also asked at AutoSpot
- Tell us about yourself as a developer — experience, stack, projects.
- What are your salary expectations?
- Do you have experience writing and working with native SQL queries or similar low-level commands to a database?
- What AI tools do you use and for what tasks?
- Which design patterns have you used in real-world work, and in what situations?
Similar questions
- Is it possible to explicitly specify the use of an index in the WHERE clause to speed up the search?
- Please give examples of SQL commands that acquire locks.
- What should you avoid doing inside a transaction?
- How do you optimize SQL queries? What do you use for this?
- What are the standard transaction isolation levels?