Saturday, October 15, 2016

Primary key in SQL Server

Primary key is a single field or combination of fields that uniquely defines a record.
None of the fields that are part of the primary key can contain a null value.
A primary key column cannot contain NULL values.
Each table can have only ONE primary key.

We can create a primary key in table with the CREATE TABLE statement.
Syntax

The syntax to create a primary key using the CREATE TABLE statement:

CREATE TABLE table_name
(
  column1 datatype { NULL | NOT NULL } PRIMARY KEY,
  column2 datatype { NULL | NOT NULL },
  ...
 
);

Example :

CREATE TABLE Persons
(
Employee_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Department varchar(255),
Salary money
)


DROP a PRIMARY KEY Constraint

We can also drop the PRIMARY KEY constraint, using the below example:

ALTER TABLE Employee
DROP CONSTRAINT pk_EmployeeID