聚集索引和非聚集索引之间的区别是什么?


当前回答

聚集索引

聚集索引检索更快,插入更慢 和更新。 一个表只能有一个聚集索引。 不需要额外空间来存储逻辑结构。 确定在磁盘上存储数据的顺序。

非聚簇索引

非聚集索引在检索数据时较慢,在检索数据时较快 插入和更新。 一个表可以有多个非聚集索引。 需要额外的空间来存储逻辑结构。 对磁盘上存储数据的顺序没有影响。

其他回答

聚类基本上意味着数据在表中的物理顺序。这就是为什么每个表只能有一个。

非聚集意味着它“只是”一个逻辑顺序。

聚集索引

聚集索引检索更快,插入更慢 和更新。 一个表只能有一个聚集索引。 不需要额外空间来存储逻辑结构。 确定在磁盘上存储数据的顺序。

非聚簇索引

非聚集索引在检索数据时较慢,在检索数据时较快 插入和更新。 一个表可以有多个非聚集索引。 需要额外的空间来存储逻辑结构。 对磁盘上存储数据的顺序没有影响。

//复制自MSDN,其他答案中没有明确提到非聚类索引的第二点。

集群

Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be stored in only one order. The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.

非聚集

Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.

优点:

聚集索引适用于范围(例如:select * from my_table where my_key在@min和@max之间)

在某些情况下,如果使用orderderby语句,DBMS将不需要做排序工作。

缺点:

聚集索引可能会减慢插入速度,因为如果新键不是按顺序排列的,那么在放入记录时必须修改记录的物理布局。

聚集索引

每张桌子只有一个 由于数据按索引顺序物理存储,因此读取速度比非集群更快

非聚类索引

每张表可以使用多次吗 插入和更新操作比聚集索引更快

当选择使用索引的字段的数据时,这两种类型的索引都将提高性能,但会降低更新和插入操作的速度。

由于插入和更新较慢,聚集索引应该设置在一个字段上,通常是增量的,即Id或时间戳。

SQL Server通常只使用选择性高于95%的索引。