Sunday, August 16, 2020

Primary Key Constraint in SQL Server

 The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values.

primary key constraints are implemented as unique indexes. By default, SQL Server creates a primary key as a unique clustered  index, although it is not a requirement. We can have nonclustered primary keys, or we can even have tables with no primary keys at all.

A table can have one primary key and a primary key can consist of single or multiple columns.

Example:

CREATE TABLE Persons (

    ID int NOT NULL,

    LastName varchar(255) NOT NULL,

    FirstName varchar(255),

    Age int,

    CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)

);

Since 
In this case the primary key has two or more columns, you must use the PRIMARY KEY constraint as a table constraint.

In this example either ID or LastName value can be duplicate but combination of the two columns can't be duplicate.

Following table is created with out primary key.

CREATE TABLE events_cat(

    event_id INT NOT NULL,

    event_name VARCHAR(255),

    start_date DATE NOT NULL,

    duration DEC(5,2)

);

To make the event_id column as the primary key, you use the following ALTER TABLE statement:

 ALTER TABLE events_cat ADD PRIMARY KEY(event_id);

 Note that if the events_cat table already has data, before promoting the event_id column as the primary key, you must ensure that the values in the event_id are unique.

Different types of SQL Server Constraints:

Unique Constraint in SQL Server

 Unique constraint enforce uniqueness of the values in a column. It ensures all the values in a column are different. This can be created on Nullable columns and would thus treat NULL as one of the possible value.

Like primary keys, unique constraints belong to the logical database design and are implemented as unique, nonclustered indexes on the physical level.

We can have many unique constraints per table.

It is a good idea to have uniqueness enforced when data is unique. This helps to keep the data clean and avoids data integrity issues. Unique constraints can also help Query Optimizer to generate more efficient execution plans.

Example:

create table dbo.Employee_Details

(

EmployeeId int not null,

Name nvarchar(64) not null,

SSN char(9) not null constraint UQ_Employees_SSN unique,

DepartmentCode varchar(32) not null,

IntraDepartmentCode varchar(32) not null,

constraint UQ_Employees_Codes unique(DepartmentCode, IntraDepartmentCode)

)


Alter and Drop Constraint

Alter table Employee_Details add constraint Employee_Details_UK unique(EmployeeId)

Alter table Employee_Details drop constraint Employee_Details_UK

Different types of SQL Server Constraints: