What is a Primary Key?
A Primary Key is a unique ID for each row. Like your student ID or passport number.
Simple rule: No two rows can have the same Primary Key.
How Primary Key Works
Basic Syntax
CREATE TABLE students (
student_id INTEGER PRIMARY KEY,
name VARCHAR(100),
age INTEGER
);Example 1: Auto-Generated IDs
Let database create IDs automatically:
CREATE TABLE students (
student_id SERIAL PRIMARY KEY,
name VARCHAR(100)
);Example 2: Insert with Primary Key
INSERT INTO students (name) VALUES ('John'); -- Gets ID 1
INSERT INTO students (name) VALUES ('Mary'); -- Gets ID 2Example 3: Find by Primary Key
SELECT * FROM students WHERE student_id = 1;Primary Key Rules
- Must be unique - No duplicates
- Cannot be NULL - Must have value
- One per table - Only one Primary Key
- Never changes - Don't modify it
Try It Below
Use the playground to practice:
SELECT * FROM students WHERE student_id = 1;SELECT student_id, name FROM students;
What Comes Next
Next: Learn Foreign Keys to connect tables together.