r/SQL • u/scientecheasy • Jul 29 '26
MySQL SQL Query Execution Lifecycle
Diagram illustrating the SQL query execution lifecycle, showing query submission, parsing, optimization, execution, and result delivery in a database.
78
Upvotes
View all comments
Show parent comment
3
u/mikeblas Jul 30 '26
Some engines do evaluate multiple plans. SQL Server does, for one (or at least did, back when I worked on it). The engine knows many transformations that it can apply on the execution tree which will result in a semantically equivalent candidate plan. It measures cost, then applies the translation, then measure cost again, keeping the best plans. It memoizes subtrees to keep the cost of evaluation down, and tries to prune the explosive combinatorial problem, and so on.
Statistics influence the cost computation, not the plan generation.
A HASH_JOIN B WHERE A.COL < 100might be cheaper or more expensive thanB HASH_JOIN A WHERE A.COL < 100depending on the number of rows that come through the filter, and that cardinality is estimated by looking at statistics.But the SQL Server query optimizer certainly does produce and evaluate multiple plans.
The explanation of optimizer timeous is the reference I could most quickly find. Probably something better out there if you spend the time. You might also try screwing around with some of the optimizer trace flags so that it dumps it's progress. I think there's one or two in public builds that gives some insight into the search -- or at least, the transformation rules applied.