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 公众号,将有更多精彩内容分享:

                                                                 

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值