How does the query optimizer use table statistics and cardinality estimates to choose an execution plan?
Last updated
The cost-based optimizer uses statistics (row counts, distinct values, histograms, null fractions) to estimate cardinality, the number of rows each operation produces.
Those estimates drive join order, join algorithm (nested loop, hash, merge), and index-vs-scan choices. The plan with the lowest estimated I/O and CPU cost wins.
Stale or skewed stats and correlated columns cause misestimates and bad plans. Refresh them with
ANALYZEorUPDATE STATISTICS.
- https://learn.microsoft.com/en-us/troubleshoot/sql/database-engine/performance/troubleshoot-optimizer-timeout-performance
- https://medium.com/@pranavsb699/cost-based-optimizer-cbo-in-oracle-best-of-mrcaption49-88d7d66b268b
- https://learn.microsoft.com/en-us/sql/relational-databases/performance/cardinality-estimation-sql-server?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-show-statistics-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/relational-databases/statistics/view-statistics-properties?view=sql-server-ver17
- https://www.postgresql.org/docs/current/planner-stats.html
- https://medium.com/@kishorev1/demystifying-oracles-cost-based-optimizer-a-deep-dive-into-performance-tuning-cd1282a50dc5
- https://www.postgresql.org/docs/current/multivariate-statistics-examples.html