How do you optimize a slow-running SQL query?

Instruction: Discuss strategies and best practices for query optimization.

Context: This question addresses the candidate's skill in enhancing database performance and efficiency, critical for large-scale applications.

Updated

Official answer

Capture the exact query, parameters, expected result and representative workload. Determine whether delay comes from execution, lock waits, network transfer or application behavior before changing the SQL.

Inspect the plan. In PostgreSQL, EXPLAIN shows estimates; EXPLAIN ANALYZE executes the statement and records actual behavior. Do not run the latter on a modifying statement as if it were read-only. Compare estimated and actual row counts, repeated loops, scans, sorts/spills and I/O where available.

Check statistics and selectivity, remove unnecessary rows or columns without changing semantics, and evaluate targeted indexes against read benefit, storage and write cost. A sequential scan can be the right choice. A CTE, window function, partition or different join form is not inherently faster.

Verify results on duplicates, NULLs and boundary cases, then measure before and after under comparable cache, concurrency and parameter conditions. Consider operational locking and rollout cost for schema changes. Keep the smallest demonstrated improvement and report the workload and remaining bottleneck instead of promising universal speedup.

Related Questions