Slowdown of Queries with ORDER BY Clause
MySQL database users have encountered a puzzling performance issue related to the use of the ORDER BY clause. When added to a complex query with multiple joins and subqueries, the query's execution time increases significantly from milliseconds to seconds.
One specific instance involves a query that retrieves data from three tables with approximately 40,000 rows in the largest table. Without the ORDER BY clause, the query performs optimally. However, when any column is used as a sorting criteria, the query slows down by several orders of magnitude to around 10 seconds.
The root cause of this issue lies in the database's optimization mechanism. By default, MySQL attempts to optimize queries by creating temporary tables or using subqueries. When an ORDER BY clause is added, the optimizer miscalculates the size of the temporary table needed and allocates an insufficient amount of memory. Consequently, the query falls back to a less efficient sorting algorithm, which results in the observed slowdown.
One possible workaround is to rewrite the query using a correlated subquery or a CTE (Common Table Expression) to explicitly specify the sorting step. This allows the optimizer to correctly estimate the temporary table size, preventing the slowdown.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3