聚集索引和非聚集索引之间的区别是什么?
当前回答
//复制自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.
其他回答
聚集索引实际上描述了记录在磁盘上物理存储的顺序,因此只能有一个聚集索引。
非聚集索引定义的逻辑顺序与磁盘上的物理顺序不匹配。
聚集索引物理地存储在表上。这意味着它们是最快的,并且每个表只能有一个聚集索引。
非聚集索引单独存储,您可以拥有任意数量的索引。
最好的选择是在最常用的唯一列上设置聚集索引,通常是PK。在表中应该始终有一个精心选择的聚集索引,除非有一个非常令人信服的理由——想不出一个,但是,嘿,可能有——不这样做。
你可能已经阅读了以上文章中的理论部分:
-聚类索引,我们可以看到直接指向记录,即它的直接,所以它需要更少的时间进行搜索。此外,它不会占用任何额外的内存/空间来存储索引
而在非聚集索引中,它间接指向聚集索引,然后它将访问实际的记录,由于它的间接性质,它将花费更多的时间来访问。此外,它需要自己的内存/空间来存储索引
群集索引对磁盘上的数据进行物理排序。这意味着索引不需要额外的数据,但只能有一个聚集索引(显然)。使用聚集索引访问数据是最快的。
All other indexes must be non-clustered. A non-clustered index has a duplicate of the data from the indexed columns kept ordered together with pointers to the actual data rows (pointers to the clustered index if there is one). This means that accessing data through a non-clustered index has to go through an extra layer of indirection. However if you select only the data that's available in the indexed columns you can get the data back directly from the duplicated index data (that's why it's a good idea to SELECT only the columns that you need and not use *)
聚类索引本质上是索引列中数据的排序副本。
聚集索引的主要优点是,当查询(seek)在索引中定位数据时,不需要额外的IO来检索该数据。
维护聚集索引的开销,特别是在频繁更新的表中,可能会导致性能较差,因此最好创建非聚集索引。
推荐文章
- 比较两个SQL Server数据库(模式和数据)的最佳工具是什么?
- 在SQL中,如何在范围中“分组”?
- 选项(RECOMPILE)总是更快;为什么?
- 设置数据库从单用户模式到多用户
- 我如何转义一个百分比符号在T-SQL?
- SQL Server恢复错误-拒绝访问
- 为什么PostgreSQL要对索引列进行顺序扫描?
- 如何在SQL Server Management Studio中查看查询历史
- SQL Server索引命名约定
- 可以为公共表表达式创建嵌套WITH子句吗?
- SQL Server的NOW()?
- 在SQL Server中截断(不是四舍五入)小数位
- 如何在SQL Server数据库中更改列数据类型而不丢失数据?
- 保持简单,以及如何在一个查询中执行多个CTE
- 如何使用TSQL截断数据库中的所有表?