为什么不使用SQL Server索引?

时间:2015-07-08 15:25:32

标签: sql sql-server

我的大多数SQL查询都有WHERE rec_id <> 'D';,例如:

 select * from Table1 where Field1 = 'ABC' and rec_id <> 'D'

我在REC_ID添加了索引。但是,当我运行此查询并查看执行计划时,不使用新索引(REC_ID)。执行计划在Field1中显示50%nonclustered index 50% RID LookupTable1(Heap)的费用。

为什么没有使用索引REC_ID

2 个答案:

答案 0 :(得分:3)

For this query:

select *
from Table1
where Field1 = 'ABC' and rec_id <> 'D';

The best index is table1(Field1, rec_id).

However, your query may not be able to take advantage of an index. The goal of using an index for a where clause is to reduce the number of pages that need to be read. To understand the concept for non-clustered indexes on normal rows, you need some basic ideas:

  • Records are stored on pages.
  • Each page is 8,192 bytes (slightly fewer used for data) and can store some number of records.
  • The entire page is loaded into memory to read a record.

Say a record is about 80 bytes and there are 100 records on each page. If 10% of the records have Field1 = 'ABC', then there will be about ten on each page. That means that using the index would not (typically) save any page reads. If 1% of the records match, then there is about one on each page. The index still isn't helpful.

If only 0.01% of the records match (30 in your case), then only a fraction of the pages need to be read. This is the sweet spot for indexes, and where they are really helpful.

The number of matching records is called "selectivity". If the where clause is not very selective, then a non-clustered index will not be useful.

Sometimes, a clustered index can be helpful in this situation. However, clustered indexes may have more overhead for insert and certain update transactions. So, the choice of index needs to be based on the queries being processed and other ways that the table is used.

答案 1 :(得分:2)

SQL Server使用许多因素来决定使用哪些索引。必须确定使用Field1上的索引比使用rec_id上的索引更有效 - 这意味着field1={value}根据数据分散定义了比rec_id <> {value}更小的集合等等,因此与其他条件相比较的记录较少。请注意,实际值通常与确定使用哪个索引无关。