Optimize query performance on a billion-row table

Instruction: Discuss strategies to optimize query performance on a table with over a billion rows in a SQL database.

Context: This question tests the candidate's knowledge of SQL query optimization techniques, indexing, and partitioning strategies for large datasets.

Updated

Official answer

A billion rows describe size, not the bottleneck. Identify the engine, exact query, parameters, concurrency, data distribution and latency target. Separate lock waits, CPU, I/O, network transfer and result materialization.

Inspect estimates and, in a safe environment, actual execution statistics. Look for unwanted row multiplication, unselective predicates, large sorts/spills, skew and stale statistics. A full scan can be appropriate for a query that needs most rows; an index is not automatically better.

Choose indexes from predicate combinations, ordering and write costs. Consider partitioning only when pruning or lifecycle management fits the workload. Compare preaggregated results when their refresh delay is acceptable. EXISTS and IN may produce equivalent plans, and rewriting NOT IN without respecting NULL semantics can change results.

Limit unnecessary columns and work while preserving the required answer. Compare result sets for duplicates, NULLs, date boundaries and ties. Benchmark comparable data, cache state and concurrency; report measured latency and resource costs, not an assumed percentage improvement.

Plan index-build locks, storage headroom and rollback before deploying. EXPLAIN ANALYZE executes the statement, so use particular care with data-changing SQL.

Source

PostgreSQL 16: plan interpretation and execution.

Related Questions