I have these two queries :
SELECT *
FROM ActionMessage am
JOIN vTasks vt ON am.TasksSeq = vt.TasksSeq
JOIN Tasks t2 ON t2.TasksSeq = vt.UltimateParent
WHERE vt.UltimateParent = 1225
SELECT *
FROM ActionMessage am
JOIN vTasks vt ON am.TasksSeq = vt.TasksSeq
JOIN Tasks t2 ON t2.TasksSeq = vt.UltimateParent
WHERE t2.TasksSeq = 1225 -- NOTE: this is the difference between
The vTasks is a view that ,using left self-joins can go up to 4 levels, calculates the top-most parent of a given task.
When I run the queries the first one takes less than a sec but the second one takes 15 secs.
Then I had a look at their actual execution plans which I attached the image link if needed.
If you have a look at the picture there is an index seek operation in both of them.
It takes 30% of the whole query exec time according to the first plan.
The first plan belongs to the query with longer exec time.
So I can conclude that index seek would take 5 secs for the query 1.
We have the same operation in plan 2 but it clearly takes less than a sec to run.
I had a look at details of this operation in both plans but the stats and info looks the same.
My question is as the 2 queries are pretty much the same I at least expect the index seek in both would do the same operation. So Why are the execution time of them are this different?

Here is a broader view of plan 2:

In your first query you have a JOIN that tells the DBMS to do an Clustered Index Scan over an indexed entity that is Tasks table that will merged with the checking related parts to Tasks table as aliased by t2 in WHERE statement, So you will have only one Clustered Index Scan at all.
But when in your second query you try to check over your view, DBMS will again load Tasks data -that is used by your view- in a new place of memory and do another Clustered Index Scan over that new loaded data.
I suggest you to optimize ActionMessage table that makes more effects in your query by adding an Index seek (Non-Clustered).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With