Click here to Skip to main content
15,606,999 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I work on SQL server 2012 I face issue when add this statement it take 9 minutes to display 900 rows only

SELECT fmat.Value as PLID,c.CodeTypeId,
COUNT(DISTINCT tr.PartID) [#partsHasCodes]
into #partsHasCodes
FROM Parts.TradeCodes tr WITH(NOLOCK) 
INNER JOIN Parts.Nop_Part pt WITH(NOLOCK) ON pt.PartID = tr.PartID
INNER JOIN Parts.Nop_PartsFamilyAttribute fmat WITH(NOLOCK) ON  fmat.PartFamilyID=pt.PartsFamilyID AND fmat.[Key]=20281007
inner join #TempPlAndCodeType c on (c.CodeTypeId=tr.CodeTypeID)
GROUP BY fmat.Value,c.CodeTypeId

without add this statement below


query take 3 minute to display 900 rows and after add


it take 9 minutes

when join with temp table #TempPlAndCodeType time become 9 minutes.

What I have tried:

this is execution plan so what I do

what I do as below :
create clustered index idx on #TempPlAndCodeType (CodeTypeId)

but still take too much time
Updated 6-Aug-20 0:22am
[no name] 5-Aug-20 20:50pm    
In case of MS SQL: Keep in mind, MS SQL does not automatically add an index for foreign keys ;)
ahmed_sa 5-Aug-20 21:02pm    
so please what I do
Gerry Schmitz 6-Aug-20 2:12am    
Simplify or continue to toil away.

1 solution

According to your estimated execution plan, you're joining nearly 50 million rows to over 26 million rows, then joining to another 3.5 million rows. Your server will need to use over 1.33GB of memory to process that query.

The fact that your final (estimated) output is only 7 thousand rows is irrelevant. SQL still has to process the millions of rows in your source tables to get to that result.

Start by looking at your actual execution plan, instead of your estimated plan. Try running the Database Engine Tuning Advisor to see what indexes it recommends for your query - but don't just blindly apply them; evaluate the recommendations carefully, considering your normal expected database workload.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900