MDEV-38877: Unnecessary filesort on derived table materialization#4722
Open
OmarGamal10 wants to merge 1 commit intoMariaDB:12.3from
Open
MDEV-38877: Unnecessary filesort on derived table materialization#4722OmarGamal10 wants to merge 1 commit intoMariaDB:12.3from
OmarGamal10 wants to merge 1 commit intoMariaDB:12.3from
Conversation
Fixes unnecessary filesort on derived tables when ordered/grouped by a field in the key. The data is inherently sorted, wrapping the result set in a filesort is redundant.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why it happens?
The optimizer flags outer references for subqueries as constants, so that for every re-execution for the subquery, index is skipped, as filtering on a constant makes all rows have the same value already.
Consider this example
SELECT * FROM t2 JOIN (SELECT groups_20, MAX(b) FROM t1 GROUP BY groups_20) DT ON t2.a = groups_20;After hours of investigation, I found that the index is bypassed because
table->const_key_partsincorrectly flags the[GROUP/ORDER] BYcolumn as a constant. This optimization is correct for Nested Loop / Lateral joins since the subquery is re-executed for each outer row, the join column is a literal constant in this context, making index usage/sorting redundant.However, if the optimizer decides to materialize the subquery, the subquery is executed once to build a table. In this context, the column is a variable, not a constant.
The fix is a guard condition to prevent treating an outer reference as a constant in case of derived tables.
Before