Junior — Middle
How to identify the most resource-intensive SQL queries in a database?
sobes.tech AI
Answer from AI
To identify the most resource-intensive SQL queries in a database, the following approaches can be used:
- Enable slow query logging in the DBMS to record queries that run longer than a specified threshold.
- Use built-in profiling and monitoring tools of the DBMS, such as
EXPLAINorEXPLAIN ANALYZEin PostgreSQL, to understand the execution plan and estimate costs. - In systems like MySQL, you can use
SHOW PROCESSLISTor Performance Schema to analyze current queries. - In Python, query profiling can be integrated via ORM (e.g., SQLAlchemy) or middleware that logs query execution times.
Example of using EXPLAIN in PostgreSQL:
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123;
This will show how long the query takes and which indexes are used.