--(1)索引:索引就是数据表中数据和相应的存储位置的列表,利用索引可以提高在表或视图中的查找数据的速度
--(2)索引分类:数据库中索引主要分为两类:聚集索引和非聚集索引。它们是数据库引擎中索引的基本类型,是理解其他类型索引的基础
/*(3)聚集索引:是指表中数据行的物理存储顺序和索引的存储顺序完全相同。聚集索引根据索引顺序物理地重新排列了用户插入到表中的数据,因此,每个表只能创建一个聚集索引。聚集索引经常创建在表中经常被搜索到的列或按顺序访问的列上。在默认情况下,主键越苏自动创建聚集索引*/
/*(4)非聚集索引:A、非聚集索引不改变表中数据列的物理存储位置,数据与索引分开存储,通过索引指向的地址与表中的数据发生关系。
B、非聚集索引没有改变表中的物理行的位置,索引可以在以下情况下使用非聚集索引:1.如果某个字段的数据唯一性比较高;2.如果查询所得到的数据量比较少;*/
/*(5)其他索引:
1.唯一索引:如果希望索引键都不同,可以创建唯一索引。聚集索引和非聚集索引都可以是唯一索引;
2.包含新列索引:索引列的最大数量是16个,索引列的字节总数的最高值是900。如果当多个列的字节数大于900,却又想在这些列中都包含索引,可以使用包含新列索引;
3.视图索引:提供视图查询效率,可以使视图的索引物理化,也就是说将结果集永久存储在索引中,可以创建视图索引;
4.XML索引:是与XML数据关联的索引形式,是XML二进制blob的已拆分持久表示形式;
5.全文索引:一种特殊类型的基于标记的功能性功能,用于帮助在字符串中搜索赋值的词。*/
/*(6)基本语法:create [unique] [clustered | noclustered]
index index_name
on table name(column_name ...)
[with fillfactor=x]
unqiue:唯一索引
clustered:聚集索引
noclustered:非聚集索引
fillfactor:填充因子大小,范围在0-100之间,表示索引页填满的空间所占的百分比。*/
/*(7)适合创建索引的列:当数据库的某一列被频繁的用于数据库查询时,或者该列用于数据库进行排序时可以创建索引;
(8)不适合创建索引的列:如果列中有几个不同的值,或者表中仅包含几行值,则不推荐为其创建索引。因为索引在搜索数据所花的时间比在表中逐行搜索的话时间更长。
*/
--示例:
if(exists(select * from sys.indexes where name='idx_stu_name'))
drop index studentB.idx_stu_name
go
create index idx_stu_name
on
studentB(name);
--联合索引
if (exists (select * from sys.indexes where name = 'idx_uqe_clu_stu_name_age'))
drop index student.idx_uqe_clu_stu_name_age
go
create unique clustered index idx_uqe_clu_stu_name_age
on student(name, age);
if (exists (select * from sys.indexes where name = 'idx_cid'))
drop index student.idx_cid
go
if (exists (select * from sys.indexes where name = 'idx_cid'))
drop index student.idx_cid
go
--非聚集索引
create nonclustered index idx_cid
on
student (cid)
with fillFactor = 30; --填充因子
--聚集索引
if (exists (select * from sys.indexes where name = 'idx_sex'))
drop index student.idx_sex
go
create clustered index idx_sex
on
student(sex);
--聚集索引
if (exists (select * from sys.indexes where name = 'idx_name'))
drop index student.idx_name
go
create unique index idx_name
on
student(name);