A primary key in SQL Server is a column or set of columns that uniquely identifies each row in a table.
The primary key
serves as the table's main point of reference and ensures that no two rows have the same values.
It also enforces data integrity by preventing duplicate or null values from being inserted into the table.
In addition to these features, a primary key also creates a clustered index
on the table, which can improve query performance.
Primary keys are defined when the table is created, and can be used to create relationships with other tables in the database.
Add Constraint Primary Key Example
To create a primary key in a table, use the command alter table with add constraint.
Departments table
USE tempdb;
GO
CREATE TABLE dbo.departments(
id int NOT NULL,
name varchar(250) );
GO
Create Constraint Primary Key
USE tempdb;
GO
ALTER TABLE dbo.departments
ADD CONSTRAINT PK_DEP_ID PRIMARY KEY CLUSTERED (ID);
GO