Erik Darling digs into a problem. Part 1 sets up the scenario:
Here’s the query plan, which yes, you’re reading correctly, runs for ~23 seconds, fully joining both tables prior to doing the final aggregation.
I’m showing you a little extra here, because there are missing index requests that the optimizer asks for, but we’ll talk about those in tomorrow’s post.
The wait stats for this query, since it’s running in Batch Mode, are predictably HT-related.
Part 2 covers those missing indexes:
I’ve taken a small bit of artistic license with them.
The crappy thing is… They really do not help and in some cases things get substantially worse.
Maybe it’s because it’s early and I’m trying to compile things in my head rather than actually trying it out, but it seems like a combo of CTE + CROSS APPLY
or a pair of CROSS APPLY
statements could work better (especially with a good index), assuming that join doesn’t need to be in place. Given the query as it is, with two MAX()
aggregations and no GROUP BY
clause, that could be an avenue for improvement, though one I have not actually tested. Nonetheless, read both of Erik’s posts.