Performance Tuning SQL

丶灬走出姿态 提交于 2019-12-11 00:47:11

问题


I have the following sql. When I check the execution plan of this query we observe an index scan. How do I replace it with index seek. I have non clustered index on IdDeleted column.

SELECT Cast(Format(Sum(COALESCE(InstalledSubtotal, 0)), 'F') AS MONEY) AS TotalSoldNet,
       BP.BoundProjectId                                               AS ProjectId
FROM   BoundProducts BP
WHERE  BP.IsDeleted=0 or BP.IsDeleted is null
GROUP  BY BP.BoundProjectId

I tried like this and got index seek, but the result was wrong.

SELECT Cast(Format(Sum(COALESCE(InstalledSubtotal, 0)), 'F') AS MONEY) AS TotalSoldNet,
       BP.BoundProjectId                                               AS ProjectId
FROM   BoundProducts BP
WHERE  BP.IsDeleted=0
GROUP  BY BP.BoundProjectId 

Can anyone kindly suggest me to get the right result set with index seek.

I mean how to I replace (BP.IsDeleted=0 or BP.IsDeleted is null) condition to make use of index seek.

Edit, added row counts from comments of one of the answers:

null: 254962 rows
0:    392002 rows
1:     50211 rows

回答1:


You're not getting an index seek because you're fetching almost 93% of the rows in the table and in that kind of scenario, just scanning the whole index is faster and cheaper to do.

If you have performance issues, you should look into removing format() -function, especially if the query returns a lot of rows. Read more from this blog post

Other option might be to create an indexed view and pre-aggregate your data. This of course adds an overhead to update / insert operations, so consider that only if this is done really often vs. how often the table is updated.




回答2:


have you tried a UNION ALL? select ... Where isdeleted = 0 UNION ALL select ... Where isdeleted is null

Or you can add an Query hint (index= [indexname])

also be aware that the cardinality will determine if SQL uses a seek or a scan - seeks are quicker but can require key lookups if the index doesnt cover all the columns required. A good rule of thumb is that if the query will return more than 5% of the table then SQL will prefer a scan.



来源:https://stackoverflow.com/questions/32971763/performance-tuning-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!