SQL Tutorial - Primary Key Constraint


'Primary Key Constraint' is used on a column to ensure that the values being entered in the specified column are distinct and not null so that it helps in uniqely identifying that row.

Primary Key Constraint


The 'Primary Key Constraint' ensures that all values in this column or set of columns are unique and also not null. This is the main difference between 'Unique' and "Primary Key' constraints. Here also there are no duplicate values.

SQL 'Primary Key Constraint' Syntax


CREATE Table tablename
(
column1 datatype PRIMARY KEY,
column2 datatype,
column3 datatype,
column4 datatype,
.
.
.
columnn datatype
)

The above method of creating a table creates an 'Primary Key' constraint on column1 at the column level as it is defined as part of a column definition.

The Primary Key Constraint Example


CREATE TABLE Employees
(
EmployeeID smallint PRIMARY KEY,
EmployeeName nvarchar(50) NOT NULL,
DateOfBirth smalldatetime NOT NULL,
DesignationID smallint NULL,
DeptID smallint NULL,
PhoneNo nvarchar(12) NULL,
City nvarchar(50) NOT NULL,
Salary decimal(5, 2) NULL
)

Note: When creating the columns, the data type of the column must be given so that you know what datatype it holds. If it's a non integer, you need to specify the length of the column also. Here we are ensuring that 'EmployeeID' column is a primary key ie. it is a non null and unique value.