Primary key、unique、index之间的关系

时间:2022-09-16 08:42:43

参考文献

Difference between an Index and a Primary Key

本质区别

首先primary key跟unique都是Constraints,属于logical object,而index则是physical object,会占用index page并被保存在磁盘上。

Primary key Constraints和unique Constraints

Primary key Constraints和unique Constraints都需要保证列是唯一的,不能有重复值,但是一张表只能有一个Primary key Constraints,但是可以有多个unique Constraints。还有就是Primary key Constraints是非空的,但是unique Constraints允许为空。不过需要注意的是,因为在SQL Server中可以NULL==NULL,所以unique列只允许只有一个NULL值。具体参考UNIQUE Constraints。实例验证如下

use TESTDB3
go
--1.创建表
create table t1
(
    stuid int unique,
    stuname nvarchar(10)
);
go

--2.插入两条记录,有一列是null
insert t1 values(1,'xuwei');
insert t1 values(null,'xuwei');
select * from t1;

--3.在unique约束的列中再次插入null值
insert t1 values(null,'xuwei');

Primary key 和index

When you specify a PRIMARY KEY constraint for a table, the Database Engine enforces data uniqueness by creating a unique index for the primary key columns. This index also permits fast access to data when the primary key is used in queries. Therefore, the primary keys that are chosen must follow the rules for creating unique indexes. --------PRIMARY KEY Constraints

创建primary key的时候肯定会创建一个unique index。创建unique index 是为了提高保证primary key唯一性的效率 。试想不创建unique index,那么就是堆结构。而主键是要保证唯一的,那么每次插入一条数据都要进行一次table scan,遍历整张表。假如我们有了索引,每次只需要一次index seek就好了。效率大大提高。

unique index的主要实现方式

  1. 在创建 PRIMARY KEY 约束时,如果不存在该表的聚集索引且未指定唯一非聚集索引,则将自动对一列或多列创建唯一聚集索引。主键列不允许空值。
  2. 在创建 UNIQUE 约束时,默认情况下将创建唯一非聚集索引,以便强制 UNIQUE 约束。如果不存在该表的聚集索引,则可以指定唯一聚集索引。

索引的有序结构

所有索引都是有序的。正是因为有序,查询才能够更快。

非聚集索引的叶子节点保存的是非聚集索引键和bookmark,其中非聚集索引键是有序的。如下图所示:

Primary key、unique、index之间的关系

聚集索引的叶子节点就是数据本身,数据本身按照聚集索引键有序。如下图所示

Primary key、unique、index之间的关系