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


当前回答

聚集索引物理地存储在表上。这意味着它们是最快的,并且每个表只能有一个聚集索引。

非聚集索引单独存储,您可以拥有任意数量的索引。

最好的选择是在最常用的唯一列上设置聚集索引,通常是PK。在表中应该始终有一个精心选择的聚集索引,除非有一个非常令人信服的理由——想不出一个,但是,嘿,可能有——不这样做。

其他回答

聚集索引实际上描述了记录在磁盘上物理存储的顺序,因此只能有一个聚集索引。

非聚集索引定义的逻辑顺序与磁盘上的物理顺序不匹配。

聚集索引

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

非聚簇索引

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

聚集索引

一个表只能有一个聚集索引。 通常在主键上进行。 聚集索引的叶节点包含数据页。

非聚簇索引

一个表只能有249个非聚集索引(直到sql version 2005的后续版本支持多达999个非聚集索引)。 通常在任意键上。 非聚集索引的叶节点不包含数据页。相反,叶节点包含索引行。

//复制自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.

聚集索引

一个表中只能有一个聚集索引 对记录进行排序,并根据顺序进行物理存储 数据检索比非聚类索引快 不需要额外的空间来存储逻辑结构

非聚类索引

一个表中可以有任意数量的非聚集索引 请勿影响物理秩序。为数据行创建逻辑顺序,并使用指向物理数据文件的指针 数据插入/更新比聚类索引快 使用额外空间存储逻辑结构


除了这些差异,你必须知道,当表是非聚集的(当表没有聚集索引)数据文件是无序的,它使用堆数据结构作为数据结构。