SQL 服务器:唯一约束说明

SQL SERVER: Unique Constraint Explanation

有人可以简化向列添加 UNIQUE CONSTRAINT 的解释吗? 创建键索引时,SQL SERVER 是否复制行中的所有信息并将其添加到索引或仅添加应用了 UNIQUE CONSTRAINT 的列中的数据?

希望我解释得当。
任何帮助将不胜感激。
李.

编辑**

好的,我想我明白了吗?

CREATE TABLE dbo.test 
    (
    Id int NOT NULL, 
    Name char(10) NOT NULL UNIQUE
    );

INSERT INTO dbo.test (id, name) VALUES (1, 'Lee')
INSERT INTO dbo.test (id, name) VALUES (2, 'Paul')
INSERT INTO dbo.test (id, name) VALUES (3, 'Adam')
INSERT INTO dbo.test (id, name) VALUES (4, 'Henry')

在聚簇索引中,整个 table 将像

一样排序
3, Adam
4, Henry
1, Lee
2, Paul

因此,对于每个额外的 INSERT,服务器都必须根据名称列对整个 table 重新排序?

在非聚集索引中还有另一个 "table" 存储排序?

When creating the key index does SQL SERVER copy ALL of the information in the row and add it to the index or just the data in the column with the applied UNIQUE CONSTRAINT?

没有"key index"这样的术语。

索引可以是 clusterednon-clustered

当您声明 UNIQUE CONSTRAINT 时,它是逻辑实体,但 unique index 创建

物理支持它

当您创建 unique constraint 并将其声明为 clustered 时,将创建 clustered index。如果您在约束定义中未提及 clustered 或使用显式 nonclustered,将创建非聚集索引。

Non-clustered 索引是一个单独的数据结构,其中每一行都包含键列。

另一方面,clustered index(或者更好地称它为clustered table)是数据本身+在其上方搜索B树。在这种情况下,没有创建单独的结构,table 本身现在被组织为有序索引而不是堆。

UNIQUE CONSTRAINT 将像 UNIQUE INDEX 一样工作。有两种方式:

  • 使用 clustered index 时,行以与索引相同的顺序物理存储在磁盘上。 (因此,只有一个聚簇索引是可能的)

  • 对于 non clustered index,还有第二个列表,其中包含指向物理行的指针。您可以有许多非聚簇索引,尽管每个新索引都会增加写入新记录所需的时间。

  • 如果同时有聚集索引和非聚集索引,那么非聚集索引将指向聚集索引列。

回答会让你理解的更清楚一些。

By default the unique constraint and Unique index will create a non clustered index if you don't specify any different (and the PK will by default be created as CLUSTERED if no conflicting clustered index exists) but you can explicitly specify CLUSTERED/NONCLUSTERED for any of them.