经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MS SQL Server » 查看文章
sqlserver 筛选索引(filter index)在查询是需要注意的事项
来源:cnblogs  作者:MSSQL123  时间:2019/5/29 8:49:08  对本文有异议

 

sqlserver 的筛选索引(filter index)与常规的非筛选索引,加了一定的filter条件,可以按照某些条件对表中的字段进行索引,但是filter 索引在查询 使用上,并不等同于常规的索引,
如果忽略了这些差异,可能会造成潜在的问题,因此在使用filter索引的时候,一定要结合具体的查询,做充分的测试。

测试case

  1. if object_id('test_filter_index') is not null
  2. drop table test_filter_index
  3. GO
  4.  
  5. create table test_filter_index
  6. (
  7. id int identity(1,1) not null primary key,
  8. col2 varchar(10),
  9. col3 varchar(10),
  10. create_date datetime
  11. )
  12. GO
  13.  
  14.  
  15. --写入10W行测试数据,col2 col3非空
  16. insert into test_filter_index
  17. select concat('A',cast(rand()*1000000 as int)),concat('B',cast(rand()*1000000 as int)),getdate()
  18. GO 100000
  19.  
  20.  
  21. --写入1W行测试数据,col2 col3为空
  22. insert into test_filter_index
  23. select null,null,getdate()
  24. GO 10000

非filter索引

如果是正常的索引,也即不加filter条件,如下创建测试表上的索引

  1. --col2col3上,如果是常规索引(非筛选索引)
  2. create index idx_col2 on test_filter_index(col2,col3)
  3. GO

如下,只要是按照索引的前导列进行查询或join,都可以使用到索引

 

filter索引

如果在创建索引的时候增加filter条件

  1. --删除之前创建的索引
  2. drop index idx_col2 on test_filter_index
  3. --col2col3上,如果是筛选索引(增加col2col3上的筛选条件)
  4. create index idx_col2 on test_filter_index(col2,col3)
  5. where col2 is not null and col3 is not null
  6. GO

在执行上述的两个查询,会发现,尽管使用的查询条件为索引的前导列,但是扔无法使用到上面创建的filter索引

其实不难理解,为什么上面两种情况无法使用到创建的filter索引?由于在创建索引的时候,增加筛选条件,这个索引树种的数据,可能是不完全符合查询语义的
就比如select * from test_filter_index where col2 = 'A632395',除了 col2 = 'A632395'这个条件之外,对于col3字段,潜在两种符合条件的数据
第一种:select * from test_filter_index where col2 = 'A632395' and col3 is null
第二种:select * from test_filter_index where col2 = 'A632395' and col3 is not null
如果走了filter索引,也即idx_col2 ,查询出来的结果可能就是不完整的,因此不会使用到idx_col2 这个索引
事实上,执行计划很清楚地显示了,什么情况下才可以用到filter索引,只有查询条件的数据被filter索引的筛选条件覆盖,或者说查询条件是filter条件的子集,才有可能用到filter索引

查询是否可以使用到filter索引,只有满足当前的查询结果集,一定是属于索引的filter筛选之后的子集的情况下,才能使用到filter索引,否则都无法使用到filter索引
filter索引只能针对具体的语句进行创建,而不能作为通用的索引使用,这个比较简单,记录一下,防止犯错。

 

原文链接:http://www.cnblogs.com/wy123/p/10940285.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号