PRIMARY KEY Constraint
What is a PRIMARY KEY?
A PRIMARY KEY uniquely identifies each row in a table. It enforces two rules: the column(s) must be unique and must not contain NULL values.
Every table should have a primary key. It is the foundation for referential integrity and allows other tables to reference rows via foreign keys.
Syntax
Column-level primary key:
CREATE TABLE students (
id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50)
);Table-level (composite) primary key:
CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);When to Use
- Every table should have a primary key for data integrity
- Use a single-column key for most tables (often a SERIAL or UUID)
- Use a composite key for junction/bridge tables
Key Points
- Uniqueness — No two rows can share the same primary key value.
- NOT NULL — Primary key columns automatically cannot be NULL.
- Auto Index — PostgreSQL automatically creates a unique B-tree index on the primary key columns.
- One Per Table — A table can have only one primary key, but it can span multiple columns (composite key).
- SERIAL — Commonly paired with SERIAL or BIGSERIAL for auto-incrementing integer IDs.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
PRIMARY KEY Constraint Challenge
Write a query that solve this task: create a products table with an auto-incrementing primary key.
Expected result
A products table is created with id as the auto-incrementing primary key.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is a PRIMARY KEY?
Press Run to execute the query once the engine is ready.
More Examples
Composite primary key
Create an enrollments table where the combination of student and course is unique.
Press Run to execute the query once the engine is ready.