简体   繁体   中英

SQL performance issue in where clause

I am running a query on SQLSERVER 2008. The query is taking 4 seconds to process. I cannot understand why it's taking so long.

SELECT tbl_Operations.Workcenter
,SUM(tbl_Used_Components.Used_Quantity) as CNF_TODAY
FROM tbl_Used_Components
JOIN tbl_Pack_Division on tbl_Pack_Division.Pack_Division_ID =        
tbl_Used_Components.Pack_Division_ID
JOIN tbl_Operations on tbl_Operations.Operation_ID = tbl_Pack_Division.Operation_ID

where CONVERT(date, tbl_Pack_Division.Stop_Time) = CONVERT(date, getdate())
AND tbl_Pack_Division.Memo = 'NORMAL'
and tbl_Pack_Division.Status = 'CNF_MACH'
GROUP BY tbl_Operations.Workcenter

The problem is in the where clause. When i run the query without Where clause it runs in 0.1 second. When I add the first 2 arguments it still runs fine. But when I add the third argument on Status-field it goes wrong.

How can this be a problem? It is a selection on the same granularity as the seond one (Memo-field).

EDIT:

Status varchar(10) -- Can have 5 different values

Memo varchar(150)

Only index: Pack_Division_ID bigint

XML Execution plan

Generally if you add one more column to the where it means that it has to be read fist from the table. So without a where condition may your query could be faster even if it has more rows to aggregate because it can use indexes only, and has to read less.

If you check the EXECUTION PLAN it says you should use an index on that two column, which would give you a boost.

The problematic step is here:

<RelOp AvgRowSize="48" EstimateCPU="0.136774" EstimateIO="1.94831" 
EstimateRebinds="0" EstimateRewinds="0" EstimateRows="1" 
LogicalOp="Clustered Index Scan" NodeId="6" Parallel="false" 
PhysicalOp="Clustered Index Scan" EstimatedTotalSubtreeCost="2.08508" 
TableCardinality="124197">

 <ScalarOperator ScalarString="[MII03].[dbo].[tbl_Pack_Division].[Memo]='NORMAL'
 AND [MII03].[dbo].[tbl_Pack_Division].[Status]='CNF_MACH' 
AND CONVERT(date,[MII03].[dbo].[tbl_Pack_Division].
[Stop_Time],0)=CONVERT(date,getdate(),0)">

I think that the answer could be the low "selectivity" in your column Status, so since it tries to use all of the three values in the same time it means now more test, because the status, fitting more times then simply the first two values. However I'm not 100% sure how the optimizer working with the AND logical operators (what does mean the order)

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