Get the App
SLTechnology News&Howtos  ›  Database  › 

What is the difference between a primary key and a unique constraint in SQLServer

Shulou Source: shulou.com Published: 2022-05-31 19:33:38 10月01日 Update

What is the difference between primary key and unique constraint in SQLServer? I believe many inexperienced people don't know what to do about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

First of all, let's make it clear that the primary key, also known as the primary key constraint, is also a constraint. Take a look at the syntax for creating it and the unique constraint:

Alter table Person add constraint PK_Id primary key (Id) alter table Person add constraint UQ_Name unique (Name)

Both primary keys and unique constraints require field values to be unique, and in addition, they have the following differences:

A table can only have one primary key, but can have multiple unique constraints; the primary key field value cannot be NULL, the unique constraint field value can be NULL; primary key field can be used as the foreign key of other tables, and the unique constraint field cannot be used as the foreign key of other tables; SQL Server defaults to create a clustered index for the primary key field and a non-clustered index for the unique constraint field

Primary key, unique, but cannot be empty; unique constraint, unique, but can be empty

After reading the above, have you mastered the method of what is the difference between a primary key and a unique constraint in SQLServer? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Fields content methods more indexes problems helpless for this in addition reasons also known as multiple for this skills contracts articles experience industry grammar information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Technology Shulou Tech Info Xiaomi NVidia