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
name | grade |
---|---|
John | A |
Sarah | B |
John | C |
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_id | name | grade |
---|---|---|
1 | John | A |
2 | Sarah | B |
3 | John | C |
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_id | subject_id | grade |
---|---|---|
1 | 101 | A |
1 | 102 | B |
2 | 101 | C |
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 / Feature | What It Means |
---|---|
Unique & Not Null | SQL enforces both automatically |
Only One PRIMARY KEY | One per table (can include multiple columns) |
Composite Keys Allowed | Yes — when one column isn’t enough |
Adds an Index | Speeds up lookups and joins |
Enables FOREIGN KEYs | Links to other tables |
Keeps Data Safe | Prevents 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!