Could you explain the difference between Primary Key and Unique Index?

Technology CommunityCategory: T-SQLCould you explain the difference between Primary Key and Unique Index?
VietMX Staff asked 3 years ago

The differences between the two are:

  • Column(s) that make the Primary Key of a table cannot be NULL since by definition, the Primary Key cannot be NULL since it helps uniquely identify the record in the table. The column(s) that make up the unique index can be nullable. A note worth mentioning over here is that different RDBMS treat this differently –> while SQL Server and DB2 do not allow more than one NULL value in a unique index column, Oracle allows multiple NULL values. That is one of the things to look out for when designing/developing/porting applications across RDBMS.
  • There can be only one Primary Key defined on the table where as you can have many unique indexes defined on the table (if needed).
  • Also, in the case of SQL Server, if you go with the default options then a Primary Key is created as a clustered index while the unique index (constraint) is created as a non-clustered index. This is just the default behavior though and can be changed at creation time, if needed.