I am writting a stored procedure that will get data for a sales report. Queries are like this:
INSERT INTO @FirstQuery
SELECT t1.*, t2.*
FROM t1
LEFT JOIN t2 ON t1.idT1 = t2.idT1
LEFT JOIN t3 ON t3.idT2 = t2.idT2
WHERE t1.nonIndexedField = @parameter1
AND (t2.idT2 IS NULL
OR
(@parameter2 = 'XXX' AND t1.indexedField1 = @parameter3)
OR
(@parameter2 = 'YYY' AND t3.indexedField1 = @parameter3)
)
With those results, I then fill a second table variable:
INSERT INTO @SecondQuery
SELECT u1.*, u2.*
FROM u1
INNER JOIN u2 ON u2.idU1 = u1.idU1
WHERE u1.NONindexedField in (SELECT someField FROM @FirstQuery)
As it was being quite slow on QA environment, I watched the execution plans. First I took a look at the Estimated plan. It saw that SecondQuery was taking really long, and I realized that u1.NONindexedField didn’t have an index and was taking an estimated 97% of the total cost.
But then I took a look at the Actual plan, and it said that FirstQuery was takin 100% of total cost. I checked the estimated rows calculated on the estimated plan and it many places it estimated very few rows where the actual plan showed around a hundred thouthand (100K). I thought it was because the field missing an index was in a table with not so many rows (17K), but I created the index anyway. To my surprise, the query time was reduced from 500 to 15 seconds.
So, my question is… why such a difference in execution plans, and how come the actual plan was way off? I know that Estimated plan doesn’t really mean “an estimation of the plan” but rather “a plan with estimated row counts”, but that doesn’t explain the difference, and certanly doesn’t explain why actual plan told me that all the cost was on a query that didn’t need optimizing…
BTW, I compared relative times and the second query indeed takes around 97% of total execution time.
Thanks for reading!
If the actual plan was way off this could be caused by outdated statistics.
Have you tried updating statistics on the tables in the query.
If the statistics are out of date, this can cause the execution plans to be off. With out updated statistics your queries may be very inefficient.
the syntax for updating statistics is:
Try updating the statistics and see if you are getting more accurate execution plans.