How do you optimize a SQL query?

Instruction: Provide strategies for improving the performance of a SQL query.

Context: This question is designed to test the candidate's skills in query optimization, including indexing, query restructuring, and the use of specific SQL constructs to improve efficiency.

Updated

Official answer

Start with the required result and the workload: frequency, parameters, row counts, concurrent users and latency target. Capture a representative baseline before changing the query.

Inspect the execution plan for inaccurate row estimates, repeated work, expensive joins, sorting/spills, excessive scanned rows and lock waits. In PostgreSQL, EXPLAIN ANALYZE executes the statement; use a safe environment for expensive queries or statements with side effects.

Select a change that addresses an observed bottleneck: a useful index, a predicate rewrite, fewer unnecessary output columns, improved statistics, or aggregation at the right grain. A CTE, subquery or join is not inherently faster than another form. A sequential scan may be appropriate when much of the table is needed.

Check equivalent results, including duplicate multiplicities, NULLs, ties and boundary values. Replacing a join with EXISTS changes the result if the original intentionally returns one row per match. Then repeat measurements across representative parameters and concurrency, including write cost and storage for added indexes. Keep the change only if its measured benefit justifies its operational cost and it preserves the intended result.

Related Questions