SQL Primary Key
A Primary Key is a column (or a group of columns) in a table that uniquely identifies each row (record) in that table.
It ensures that no two rows have the same value in that column.
Key Characteristics of a Primary Key
1. Unique
  • Every value must be different.
2. Not NULL
  • It cannot contain empty or NULL values.
3. One Primary Key per Table
  • A table can have only one primary key, but it can contain multiple columns (called a composite key).
4. Used to Create Relationships
  • Other tables can reference it using Foreign Keys.
Creating a Primary Key in SQL Example 1: While Creating Table
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
Example 2: Primary Key with AUTO INCREMENT
CREATE TABLE Students (
Student_ID INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
Example 3: Composite Primary Key
CREATE TABLE StudentCourses (
Student_ID INT,
Course_ID INT,
PRIMARY KEY (Student_ID, Course_ID)
);
Sometimes two columns together create uniqueness.
Here the combination of both columns is the Primary Key.
Rules for Primary Key
A primary key:
  • Cannot contain duplicate values
  • Cannot contain NULL values
  • Should be stable (not change often)
In simple words:
A Primary Key is the unique ID of each record in a table.