Category: sql
primary key and unique key in sql
Published on 02 Jun 2026
Explanation
A Primary Key is a column
or group of columns that uniquely
identifies each row in a table.
A table can have only one
Primary Key. Primary Key values cannot
be NULL and cannot contain duplicate
values.
Code:
CREATE TABLE users ( id INT PRIMARY KEY, name VARCHAR(100) );
Explanation
Use a Primary Key when you
need a unique identifier for every
record, such as User ID, Employee
ID, or Product ID.
Code:
INSERT INTO users (id, name) VALUES (1, 'John');
Explanation
A Unique Key ensures that all
values in a column are unique.
Unlike a Primary Key, a table
can have multiple Unique Keys and
they can allow NULL values (depending
on the database).
Code:
CREATE TABLE users ( id INT PRIMARY KEY, email VARCHAR(100) UNIQUE );
Explanation
Use a Unique Key for fields
that must not have duplicate values,
such as Email Address, Phone Number,
or Username.
Code:
INSERT INTO users (id, email) VALUES (1, 'john@example.com');
Explanation
Primary Key vs Unique Key: Primary
Key uniquely identifies records and does
not allow NULL values. Unique Key
prevents duplicate values but is not
the main identifier of the table.
Code:
-- Primary Key: id -- Unique Key: email CREATE TABLE users ( id INT PRIMARY KEY, email VARCHAR(100) UNIQUE, name VARCHAR(100) );