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



————————————————
版权声明:本文为CSDN博主「三空道人」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhoujunah/article/details/85072689

发布了69 篇原创文章 · 获赞 31 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/yyws2039725/article/details/104170504