Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL execution plans - Estimated plan seems to be more accurate than Actual plan
    primarykey
    data
    text
    <p>I am writting a stored procedure that will get data for a sales report. Queries are like this:</p> <pre><code>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) ) </code></pre> <p>With those results, I then fill a second table variable:</p> <pre><code>INSERT INTO @SecondQuery SELECT u1.*, u2.* FROM u1 INNER JOIN u2 ON u2.idU1 = u1.idU1 WHERE u1.NONindexedField in (SELECT someField FROM @FirstQuery) </code></pre> <p>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...</p> <p>BTW, I compared relative times and the second query indeed takes around 97% of total execution time.</p> <p>Thanks for reading!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload