一、索引是什么?
答:索引是一种数据结构,它和表中的列有对应关系,索引是有序的,但数据的物理排序不一定是按照索引的顺序排列的。如果是按照索引排序的,则称为聚集索引;如果不是,则称之为非聚集索引。由于聚集索引会影响到数据的物理排序,所以每个表只能有一个聚集索引,但可以有多个非聚集索引。
例子解释:
1、create table t_student(
code varchar(20),
name varchar(10)
)
create [color=red]clustered [/color]index index_t_student on t_student(name)
该表数据行会按name的顺序排序
2、create table t_student(
code varchar(20),
name varchar(10)
)
create [color=red]clustered [/color]index index_t_student on t_student(code)
该表数据行会按code的顺序排序
3、create table t_student(
code varchar(20),
name varchar(10)
)
create index index_t_student on t_student(name)
该表数据行并不会按name的顺序排序
二、为什么要建索引?
索引就像字典中的目录一样,目录是有顺序的,因此索引也是有顺序的。通过目录很快的定位到要查找的字的位置。因为索引的有序性,使得查找索引是很快的,从而加快查找索引对应的数据。
三、什么情况下适合建索引
1、建聚集索引
1)表的查询频率远远大于更新频率
2)字段值唯一或重复值很少
3)经常用作为查询条件的字段,比如字段用在算符:">"、"<"、"="、"in"两边的字段
,但对于"like"不一定适合建立索引。
4)经常用作表连接的字段
5)经常用作排序、分组的字段
2、建非聚集索引
基本上和聚集索引相同,对于范围查找的字段,使用聚集索引要更快于非聚集索引
如:select * from t where a>1 则应该对a建聚集索引。
ps:
1、查看索引的存储过程:exec sp_helpindex 表
2、向sqlserver插入200000条数据:
无索引:1m26s
有索引:2m07s
查询 select * from t_organization where code=29567:
无索引:1s
有索引:0.000..s
答:索引是一种数据结构,它和表中的列有对应关系,索引是有序的,但数据的物理排序不一定是按照索引的顺序排列的。如果是按照索引排序的,则称为聚集索引;如果不是,则称之为非聚集索引。由于聚集索引会影响到数据的物理排序,所以每个表只能有一个聚集索引,但可以有多个非聚集索引。
例子解释:
1、create table t_student(
code varchar(20),
name varchar(10)
)
create [color=red]clustered [/color]index index_t_student on t_student(name)
该表数据行会按name的顺序排序
2、create table t_student(
code varchar(20),
name varchar(10)
)
create [color=red]clustered [/color]index index_t_student on t_student(code)
该表数据行会按code的顺序排序
3、create table t_student(
code varchar(20),
name varchar(10)
)
create index index_t_student on t_student(name)
该表数据行并不会按name的顺序排序
二、为什么要建索引?
索引就像字典中的目录一样,目录是有顺序的,因此索引也是有顺序的。通过目录很快的定位到要查找的字的位置。因为索引的有序性,使得查找索引是很快的,从而加快查找索引对应的数据。
三、什么情况下适合建索引
1、建聚集索引
1)表的查询频率远远大于更新频率
2)字段值唯一或重复值很少
3)经常用作为查询条件的字段,比如字段用在算符:">"、"<"、"="、"in"两边的字段
,但对于"like"不一定适合建立索引。
4)经常用作表连接的字段
5)经常用作排序、分组的字段
2、建非聚集索引
基本上和聚集索引相同,对于范围查找的字段,使用聚集索引要更快于非聚集索引
如:select * from t where a>1 则应该对a建聚集索引。
ps:
1、查看索引的存储过程:exec sp_helpindex 表
2、向sqlserver插入200000条数据:
无索引:1m26s
有索引:2m07s
查询 select * from t_organization where code=29567:
无索引:1s
有索引:0.000..s