SQL Server 索引優化—— 查詢條件中等於、大於或小於條件在索引中的順序對性能的影響

SQL Server 索引優化

—— 查詢條件中等於、大於或小於條件在索引中的順序對性能的影響

一、準備測試表和數據

use test
go
create table tradeDetail(
       id int identity(1,1)
       ,productId int
       ,tradedate datetime
       ,[description] varchar(50)
)
create nonclustered index idx_tradeDetail_pid_tdate
on tradeDetail(productId asc,tradedate asc)
with(drop_existing=on)
insert into tradeDetail(productId,tradedate,description)
values(1,GETDATE(),'productA')
go 9900
insert into tradeDetail(productId,tradedate,description)
values(2,GETDATE(),'productB')
go 5000
insert into tradeDetail(productId,tradedate,description)
values(3,GETDATE(),'productC')
go 1000

二、等於條件在索引中排列靠前,大於或小於在索引中排列靠後(見上面創建索引腳本)

set statistics io on
set statistics time on
select
       productID,tradedate
from dbo.tradeDetail
where productID=1 and tradedate>'2018-05-01'

 

三、大於或小於條件在索引中排列靠前,等於條件在索引中排列靠後(見下面創建索引腳本)

DBCC DROPCLEANBUFFERS  --清除緩衝區
DBCC FREEPROCCACHE  --刪除計劃高速緩存中的元素
create nonclustered index idx_tradeDetail_pid_tdate
on tradeDetail(tradedate asc,productId asc)
with(drop_existing=on)
set statistics io on
set statistics time on
select
       productID,tradedate
from dbo.tradeDetail
where productID=1 and tradedate>'2018-05-01'

 

從上面的兩種結果來看,查詢條件中的等於條件、大於或小於條件對應的字段在索引中的排列順序對性能有極大影響,等於條件對應字段在索引中排列靠後,其邏輯讀取26,是等於條件對應字段在索引中排列靠前的5倍多。

所以,在創建多條件查詢的索引時,等於條件對應的字段要排在大於或小於條件對應的字段之前。

四、最後關閉統計、刪除測試表

set statistics io off
set statistics time off
drop table tradeDetail

如果喜歡,可以掃碼關注SQL Server 公衆號,將有更多精彩內容分享:

                                                                 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章