简体   繁体   中英

Why is Sort operation before Nested Loops (Inner Join)?

I have 2 Sql Server instances, and one query:

SELECT 
    [DetailDescription],
    [SubTotal]
FROM [dbo].[CRR] WITH (INDEX (IX_CORM_CORMId))
WHERE CORM_CORMId >= 5933168 AND CORM_CORMId <= 5955843

This leads to 2 query execution plans: 在此输入图像描述 在此输入图像描述

Here is uploaded version

One with Sort gets 301740 rows and takes 48s, other gets 286743 rows without Sort takes 5s. One db is a bit outdated copy of other. Order of rows number in table is 98 419 368.

My questions are:

  1. I don't understand why Sort is needed for Nested Loops join? I've tried to disable it with 'OPTION (QUERYTRACEON 2340)'. The option makes no difference at all.
  2. Why is such big differnce in execution time? How to avoid this?

I use Sql Server 2014.

Update:

With STATISTICS IO:

Table 'CynergyResidualRecord'. Scan count 1, logical reads 1226357, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

The sort is to get the rows in order of CynergyResidualRecordId prior to performing the key lookups.

This is an optimisation so the lookups are less random IO discussed here .

It certainly shouldn't take 48 seconds to sort 300K rows - the plan you posted shows the Actual elapsed Time for the sort operator is 281 ms.

The actual elapsed time for the whole plan was 2.496 seconds so I'm not sure where you are getting 48 seconds from. Maybe the 48 second run encountered blocking or there is a problem with your measuring methodology.

I think this happens due to Out-dated statistics. consider updating statistics for this table.

UPDATE STATISTICS [dbo].[CRR];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM