PRIMARY KEY – Unique + Not NULL

PRIMARY KEY – Unique + Not NULL
Because every row in your table deserves to be one of a kind.

🔧 Quick Syntax to Create a PRIMARY KEY

CREATE TABLE table_name (
   column_name datatype PRIMARY KEY
);
-- For multiple columns (composite key)
CREATE TABLE table_name (
   column1 datatype,
   column2 datatype,
   PRIMARY KEY (column1, column2)
);

This tells SQL: “Make sure this column (or combo) is never empty and never duplicated.”

Real-Life Analogy: A Classroom Without Student IDs

Imagine you track student grades like this:

Without a PRIMARY KEY

namegrade
JohnA
SarahB
JohnC

Two Johns — no idea who’s who. It’s like a class without roll numbers.

Let’s Fix It: Add a PRIMARY KEY

CREATE TABLE students (
   student_id INT PRIMARY KEY,
   name VARCHAR(50),
   grade CHAR(1)
);

INSERT INTO students (student_id, name, grade) VALUES
(1, 'John', 'A'),
(2, 'Sarah', 'B'),
(3, 'John', 'C');

Output:

student_idnamegrade
1JohnA
2SarahB
3JohnC

Already Have a Table? Add PRIMARY KEY

ALTER TABLE students
ADD PRIMARY KEY (student_id);

Make sure the column is already NOT NULL and Unique.

Composite PRIMARY KEY – One Key, Two Columns

Use when no single column is unique, but a combo is.

Example Table:

student_idsubject_idgrade
1101A
1102B
2101C
CREATE TABLE results (
   student_id INT,
   subject_id INT,
   grade CHAR(1),
   PRIMARY KEY (student_id, subject_id)
);

Each row is unique by the combo of student + subject.

Don’t Do This:

-- Invalid! You can't have two primary key statements
PRIMARY KEY (student_id);
PRIMARY KEY (subject_id);

Only one PRIMARY KEY is allowed per table — it can include one or multiple columns, but must be defined in one line.

Summary Table – What to Know

Rule / FeatureWhat It Means
Unique & Not NullSQL enforces both automatically
Only One PRIMARY KEYOne per table (can include multiple columns)
Composite Keys AllowedYes — when one column isn’t enough
Adds an IndexSpeeds up lookups and joins
Enables FOREIGN KEYsLinks to other tables
Keeps Data SafePrevents duplicates, ensures structure

Recap – You Were Here

  • You started with a table full of duplicates
  • No reliable way to update or find rows
  • Now you know how to create, add, and use PRIMARY KEYs

Next up? Want to learn about FOREIGN KEYS, AUTO_INCREMENT, or compare PRIMARY KEY vs UNIQUE? Let’s keep building the SQL series!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top