What
are the differences between PRIMARY KEY and UNIQUE KEY [PRIMARY KEY VS UNIQUE KEY]?
PRIMARY KEY
|
UNIQUE KEY
|
|
Use
|
PRIMARY
KEY is used to identify a unique row (record) in a table.
|
UNIQUE
KEY is used to prevent duplicate values in a column.
|
INDEX
|
By
default, SQL-Engine creates CLUSTERED INDEX on PRIMARY KEY column if not
exists.
|
By
default, SQL-Engine creates NON-CLUSTERED INDEX on UNIQUE KEY column.
|
NULL?
|
PRIMARY
KEY does not allow or include NULL value.
|
UNIQUE
KEY allows NULL value at one time just like any other value.
|
Existence
|
A
table can have at most one PRIMARY KEY.
|
A
table can have multiple UNIQUE KEYs.
|
Reference
|
PRIMARY
KEY can be made a FOREIGN KEY into another table.
|
UNIQUE
KEY can be made FOREIGN KEY into another table.
|
Delete
|
Table
or Table row can’t be deleted if PRIMARY KEY made a FOREIGN KEY into another
table and if primary key column value is associated between tables.
|
Table
or Table row can be deleted if UNIQUE KEY made a FOREIGN KEY into another
table if unique key column value is associated between tables.
|
Examples
|
CREATE TABLE [dbo].[Employee_Unique](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[DepartmentID] [int] NOT NULL,
[EmployeeName] [varchar](50) NOT NULL,
[Gender] [char](1) NOT NULL,
[BirthDate] [date] NOT NULL,
[Salary] [decimal](10, 2) NULL,
[Detail] [varchar](max) NULL,
[IsActive] [bit] NOT NULL,
CONSTRAINT
UC_Employee UNIQUE (EmployeeID)
)
CREATE TABLE [dbo].[DegreeEmployee_Unique](
[DegreeID] [int] NOT NULL,
[EmployeeID] [int] NOT NULL,
[Sequence] [tinyint] NOT NULL,
CONSTRAINT
[PK_DegreeEmployee_DegreeID_EmployeeID] PRIMARY
KEY CLUSTERED
(
[DegreeID] ASC,
[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS
= ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DegreeEmployee_Unique] WITH CHECK ADD CONSTRAINT
[FK_DegreeEmployee_Unique_EmployeeID] FOREIGN
KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([EmployeeID])
GO
|
No comments:
Post a Comment