How would you optimize a slow-running database query?

Instruction: Describe the steps you would take to diagnose and optimize a database query that is performing poorly.

Context: This question assesses the candidate's ability to troubleshoot and optimize database performance issues, demonstrating their skills in query optimization and performance tuning.

Updated

Official answer

First reproduce the slow query with representative parameters and data. Measure elapsed time and resource use, and distinguish execution work from lock waits, network transfer and an overloaded client.

Inspect the plan and compare estimated with actual row counts where safe. Look for accidental row multiplication, poorly selective filters, large sorts or spills, repeated work and missing or stale statistics. EXPLAIN ANALYZE executes its statement; understand side effects and use an appropriate test environment, especially for writes.

Make one justified change at a time: improve the query's shape, add a workload-appropriate index, correct statistics, or introduce a maintained aggregate when its freshness contract is acceptable. An index adds write and storage costs; a sequential scan can be the right plan. Normalization does not inherently remove joins.

Verify that results remain equivalent, including duplicate rows, NULLs, boundary dates and ties. Benchmark under comparable data, cache conditions and concurrency, and report measured distributions rather than an invented percentage improvement. Monitor the deployed workload and retain a rollback path for regressions.

Source

PostgreSQL 16: using EXPLAIN.

Related Questions