How to understand if a request uses an index? How to monitor unused indexes?
sobes.tech AI
Answer from AI
To understand whether a query uses an index, the following methods are usually applied:
-
EXPLAIN plan of the query — most DBMSs (e.g., MySQL, PostgreSQL, Oracle) support the
EXPLAINcommand, which shows how the DBMS plans to execute the query, including index usage. -
Query execution monitoring — in some DBMSs, profiling or tracing can be enabled to see which indexes are involved.
-
Index usage statistics — many DBMSs keep statistics on index usage, for example, PostgreSQL has
pg_stat_user_indexes, MySQL hasinformation_schema.STATISTICSandperformance_schema.table_io_waits_summary_by_index_usage.
For monitoring unused indexes:
- In PostgreSQL, you can query
pg_stat_user_indexesand compare the number of index scans with the creation time. - In MySQL,
performance_schemacan be used to analyze index usage.
Example of an EXPLAIN query in PostgreSQL:
EXPLAIN SELECT * FROM users WHERE email = 'example@example.com';
If the plan includes Index Scan, then the index is used.
In Java applications working with the database, SQL queries can be logged and their plans analyzed through DBMS tools or ORM (for example, Hibernate supports query plan output).