建索引(尤其是主键)时请注意索引列的顺序

在我们创建主键或者其他索引时,sql server总是自动将字段的顺序设置为升序排列; 升序是默认设置,是为了保持与 SQL Server 早期版本的兼容性。建索引时索引列的顺序应该按照常用查询中的排序方式排序。

我们做个试验创建一个表,其中主键上的聚集索引按照id倒叙排列,然后分别倒叙顺序select数据,比较select的时间:
测试代码
if object_id('test_indexorder','U'is not null
begin
    
truncate table test_indexorder
    
drop table test_indexorder
end
go
create table test_indexorder
(
    id 
int identity(1,1not null,
    name 
varchar(20not null,
    content 
varchar(50not null,
    co1 
varchar(50),
    co2 
varchar(50),
    co3 
varchar(50),
    co4 
varchar(50),
    co5 
varchar(50),
    
constraint pk_testorder primary key clustered(
        id 
desc 
    )
)
go
--insert 1000000 条数据
set nocount on;
declare @t datetime;
set @t = getdate();

DECLARE @cn int;
set @cn = 1000000;
while(@cn > 0)
begin
    
insert into test_indexorder(name,content,co1,co2,co3,co4,co5)    
    
VALUES(
        
'name' + cast(@cn as varchar(10)),
        
cast(newid() as varchar(50)),
        
cast(newid() as varchar(50)),
        
cast(newid() as varchar(50)),
        
cast(newid() as varchar(50)),
        
cast(newid() as varchar(50)),
        
cast(newid() as varchar(50)));
    
set @cn = @cn -1;
end
print '插入时间(毫秒):';
print datediff(millisecond,@t,getdate());
set nocount off;
GO
checkpoint
dbcc freeproccache
dbcc dropcleanbuffers
GO
go
set nocount on;
declare @t datetime;
set @t = getdate();
with t_rn as (
    
select *,rn = ROW_NUMBER() OVER (ORDER BY id descFROM test_indexorder
)
SELECT id,name,content,co1,co2,co3,co4,co5 from t_rn WHERE rn between 19007 and 19057;
print '查询时间(毫秒)'
print datediff(millisecond,@t,getdate())

set @t = getdate();
with t_rn as (
    
select *,rn = ROW_NUMBER() OVER (ORDER BY id ascFROM test_indexorder
)
SELECT id,name,content,co1,co2,co3,co4,co5 from t_rn WHERE rn between 17007 and 17057;
print '查询时间(毫秒)'
print datediff(millisecond,@t,getdate())
set nocount off;
以下是查询时间结果
查询时间(毫秒)
393
查询时间(毫秒)
606
按照和索引相同顺序从100万条数据中取50条时需要393毫秒,相反顺序时需要606毫秒。造成的性能影响还是挺大的。

结论:
在建索引时要考虑常用查询的排序方式,在建主键时要特别注意,因为sql server会自动按照升序来建,这时候如果您的查询多数用主键列倒叙排列,记得要修改一下默认的设置。

参考资料:
http://technet.microsoft.com/zh-cn/library/ms181154.aspx
http://forums.microsoft.com/china/ShowPost.aspx?PostID=3307724&SiteID=15
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值