索引
索引和书的中的索引差不多意思,也就是书的目录。
1.聚集索引 :在聚集索引中,表中各行的物理顺序与键值的逻辑顺序相同。一个表中只可以有一个聚集索引。 如果表中有聚集索引,则该表为聚集表,如果没有则为堆的无序结构表。
2.非聚集索引:具有独立数据行的结构。包含非聚集索引键值,并且每个索引键值都有指向包含键值的数据行的指针。
创建索引
- drop table tb
- create table tb(id int,name varchar(50))
- create unique clustered index Clus_uniq_index_id on dbo.tb (id)

- exec sp_helpindex tb

- select * from sys.indexes where name='Clus_uniq_index_id'

- alter index Clus_uniq_index_id on tb disable
删除索引
DORP INDEX 表名.索引名
- select o.name,i.name
- from sys.objects o
- join
- sys.indexes i
- on o.object_id=i.object_id
- where o.name='tb'
tb Clus_uniq_index_id
统计信息是对索引的补充
- select * from sys.stats s
- join sys.objects o
- on s.object_id=o.object_id
- where o.name='tb'

使用DBCC SHOW_STATISTICS命令
第一个结果集合显示了统计信息名称,上次更新的统计信息的日期 表中记录的数量,统计信息的抽样行数,和所有索引列的平均长度。
第三个显示统计直方图的信息。。。

- exec sp_autostats 'tb'
- Global statistics settings for [ceshi]:
- Automatic update statistics: ON
- Automatic create statistics: ON
- settings for table [tb]
[Clus_uniq_index_id] ON 2012-07-23 11:18:49.420
创建统计信息
统计信息是为优化查询提供参考依据,在创建索引的时候,系统自动创建了统计信息。
- ALTER DATEABASE 数据库名 SET AUTO_CREATE_STATISTICS OFF
- create statistics ix_id on tb(id)
- exec sp_createstats
更新统计信息
- <strong>update statistics tb</strong>
- update statistics tb Clus_uniq_index_id
- update statistics tb (Clus_uniq_index_id) with fullscan
- drop statistics tb.ix_id
使用索引优化数据库效率
不宜创建索引的情形
1.对经常插入,修改,删除的数据表 不宜创建过多的索引。
2.对数据量比较小的表不必需创建索引
适合建索引的情况
1.为where子句中出现的列创建索引
2.创建组合索引。
如果多个select语句中的where子句涉及多个列可以创建一个由多个列组成的索引。
3.group不要子句出现的列创建索引
1.该列的数值是唯一的。或者说是很少有重复的
2.经常出现between....and 按顺序排序的列
3.定义为identity的唯一列
4.经常用于对数据进行排序的列
无法使用索引的Select语句
及时正确的创建了索引,在select的时候也要正确的使用。否则就是可能无法在查询过程中应用索引。
1.对索引列应用了函数。就不会走索引了
select * from tb where abs(id)=20
2.对索引列使用了like ‘%1’
select * from tb where id like '%1xxxx22' 就不会用到索引了
通配符用到后面就可以使用到索引 了
select * from tb where id like '1xxxx22%'
3.where子句对列进行了类型转换 是无法使用到索引的
select * from tb where cast(name as varchar(20))='scott';
4.组合索引的顺序很重要
- create index id_name_fsex_index on test(name,sex,id)
- select name from test where name='mrzhou' and sex='男'
- create index id_name_sex_index on test(id,name,sex)
5.where子句使用in关键字的情况
select * from Consume where cardno in ('3322','2323') 可以使用到cardno上的索引
而如果跟上子查询就会导致无法使用索引 如
select * from consume where cardno in (select cardno from creditcard where maxconsume>3000);
- select * from sys.dm_db_index_operational_stats(DB_ID(),OBJECT_ID(N'ceshi.tb'),null,null);

重新组织索引
- use ceshi
- go
- alter index Clus_uniq_index_id on tb reorganize;
- go
- use ceshi
- go
- alter index Clus_uniq_index_id on tb rebuild;
- go

浙公网安备 33010602011771号