Junior — Middle
How would you identify and analyze a slow SQL query in a system?
sobes.tech AI
Answer from AI
To identify and analyze a slow SQL query, you can follow these steps:
- Logging and monitoring: Enable slow query logging in the database (e.g., slow query log in MySQL).
- Using a profiler: Run a query profiler or use built-in DBMS tools (EXPLAIN, EXPLAIN ANALYZE) to analyze the execution plan.
- Checking indexes: Ensure that the query uses indexes rather than full table scans.
- Query optimization: Rewrite the query to reduce the number of operations, such as removing unnecessary JOINs and using aggregate functions efficiently.
- Checking statistics and index relevance: Update statistics and rebuild indexes if necessary.
Example of using EXPLAIN in PostgreSQL:
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123;
This will show how the DBMS executes the query and where bottlenecks occur.