UNIQUE and PRIMARY KEY
A primary key is the column, or set of columns, that identifies each row: no two rows may share it, and it can never be missing. Every Fee Tracker table has one. Student 103 is always Navika and only Navika; payment 7 is exactly one payment. UNIQUE is the primary key's lighter cousin: it stops duplicates in a column, such as two students with the same email, but allows missing values. This lesson covers both, what makes a good key, keys built from two columns, and how NULL behaves in unique columns.
In One Minute
UNIQUErefuses a duplicate value in a column, but allowsNULL, usually more than once.PRIMARY KEYmeansUNIQUEplusNOT NULL: every row has a value, and no two share it.- A table has at most one primary key, but may have many
UNIQUEcolumns. - A composite key spans several columns:
PRIMARY KEY (student_id, course_id). - Both create an index behind the scenes, which also makes lookups by that key fast.
UNIQUE
UNIQUE refuses a value that's already in the column. Every student's email must be different. Giving Advitha her sister's email:
UPDATE students
SET email = 'srihitha.anamaneni@example.com'
WHERE student_id = 102;ERROR: duplicate key value violates unique constraint "students_email_key"
DETAIL: Key (email)=(srihitha.anamaneni@example.com) already exists.The detail line names the column and the value that clashed. Course titles are unique too, so a second "Java OOP" is refused the same way, with courses_title_key. Like other constraints, UNIQUE can be written next to a column (email VARCHAR(80) UNIQUE) or as a table constraint (UNIQUE (email)), and added later with ALTER TABLE students ADD CONSTRAINT students_phone_key UNIQUE (phone);.
Note that "unique" means exactly equal: 'Navika@example.com' and 'navika@example.com' are different text, so both are allowed. Making uniqueness ignore case needs a unique index on lower(email), covered in Indexes.
PRIMARY KEY
A primary key is UNIQUE and NOT NULL together, and it names the row's identity. The students table's key is student_id. A second student 103:
INSERT INTO students (student_id, first_name, last_name, city, state, grade, joined_on)
VALUES (103, 'Navika', 'Anamaneni', 'Dallas', 'TX', 7, '2025-09-02');ERROR: duplicate key value violates unique constraint "students_pkey"
DETAIL: Key (student_id)=(103) already exists.And a student with no id at all:
INSERT INTO students (student_id, first_name, last_name, city, state, grade, joined_on)
VALUES (NULL, 'Navika', 'Anamaneni', 'Dallas', 'TX', 7, '2025-09-02');ERROR: null value in column "student_id" of relation "students" violates not-null constraint
DETAIL: Failing row contains (null, Navika, Anamaneni, null, null, Dallas, TX, 7, null, 2025-09-02).Both are refused, so every row in students can be found by exactly one student_id. That's what lets other tables point to a student, as payments do with student_id, which is the subject of FOREIGN KEY. A table can have only one primary key; writing PRIMARY KEY on two columns separately fails with multiple primary keys for table "t" are not allowed.
What Makes a Good Primary Key
A good key is unique, always present, and never changes. That's why the Fee Tracker uses made-up numbers (student_id, payment_id) rather than real-world facts:
| Candidate | Problem as a key |
|---|---|
email | Advitha and Navika don't have one; people change emails |
first_name, last_name | Two people can share a name; names change |
phone | Missing for Navika; numbers get reassigned |
student_id | Unique, always present, never changes: a good key |
A key made up only to identify rows is a surrogate key; one taken from real data, like an email, is a natural key. Most tables use a surrogate key, and the database can number new rows for you, as Auto-Increment and Identity shows. Real-world values that must still be unique, like email, get a UNIQUE constraint instead.
Composite Keys
A composite key is a primary key made of several columns; only the combination must be unique. An enrollment is one student in one course, so the enrollments table's key is (student_id, course_id):
CREATE TABLE enrollments (
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
enrolled_on DATE NOT NULL,
status VARCHAR(10) NOT NULL,
PRIMARY KEY (student_id, course_id)
);Srihitha (101) can be in several courses, and a course can have several students, but she can't be enrolled in Java Basics (course 1) twice:
INSERT INTO enrollments VALUES (101, 1, '2026-01-05', 'active');ERROR: duplicate key value violates unique constraint "enrollments_pkey"
DETAIL: Key (student_id, course_id)=(101, 1) already exists.Enrolling her in Git Basics (course 6), a pair that doesn't exist yet, works:
INSERT INTO enrollments VALUES (101, 6, '2026-01-05', 'active')
RETURNING *; student_id | course_id | enrolled_on | status
------------+-----------+-------------+--------
101 | 6 | 2026-01-05 | active
(1 row)NULL in UNIQUE Columns
UNIQUE treats NULL values as different from each other, so a unique column can hold many NULLs. That's why Advitha and Navika can both have no email:
SELECT student_id, email
FROM students
ORDER BY student_id; student_id | email
------------+--------------------------------
101 | srihitha.anamaneni@example.com
102 | NULL
103 | NULL
(3 rows)Two NULLs, and no clash, because one unknown isn't known to equal another. If you want at most one NULL, PostgreSQL 15 and later let you write UNIQUE NULLS NOT DISTINCT:
CREATE TABLE contacts (
email VARCHAR(80) UNIQUE NULLS NOT DISTINCT
);
INSERT INTO contacts VALUES (NULL), (NULL);CREATE TABLE
ERROR: duplicate key value violates unique constraint "contacts_email_key"
DETAIL: Key (email)=(null) already exists.Databases differ here: SQL Server's UNIQUE allows only one NULL, while PostgreSQL, MySQL and Oracle allow many. Tabs showing each database's version are coming to this course.
Keys and Indexes
Every primary key and UNIQUE constraint gets an index, the structure the database uses to check for duplicates quickly. You can see them:
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'students'
ORDER BY indexname; indexname | indexdef
--------------------+-------------------------------------------------------------------------------
students_email_key | CREATE UNIQUE INDEX students_email_key ON public.students USING btree (email)
students_pkey | CREATE UNIQUE INDEX students_pkey ON public.students USING btree (student_id)
(2 rows)The same index makes WHERE student_id = 103 and WHERE email = '...' fast, even in a table of millions of rows. Indexes explains how.
Common Mistakes
Using a real-world value as the primary key. Emails and names change or are missing. Use a surrogate key.
Expecting UNIQUE to refuse NULL. It doesn't. Add NOT NULL if the value is required.
Two PRIMARY KEY columns for a composite key. Write one table constraint: PRIMARY KEY (student_id, course_id).
Expecting UNIQUE to ignore case. 'Navika@...' and 'navika@...' are different values.
Interview Corner
What's the difference between a PRIMARY KEY and a UNIQUE constraint?
A primary key is unique and NOT NULL, and a table has at most one. A UNIQUE constraint refuses duplicates but allows NULL, and a table can have many.
What is a composite key?
A primary key made of two or more columns, where only the combination must be unique, such as (student_id, course_id) in enrollments.
Can a UNIQUE column contain several NULLs?
In PostgreSQL, MySQL and Oracle, yes, because NULLs aren't considered equal; PostgreSQL's NULLS NOT DISTINCT changes that. SQL Server allows only one NULL.
Practice
Challenge: Create a table study_buddies with student_id and buddy_id (both INTEGER NOT NULL) and a since date, where the pair is the primary key. Insert Navika (103) with Advitha (102) since 2025-09-02, and Advitha (102) with Srihitha (101) since 2025-01-13, then show the table sorted by student_id.
Show solution
CREATE TABLE study_buddies (
student_id INTEGER NOT NULL,
buddy_id INTEGER NOT NULL,
since DATE,
PRIMARY KEY (student_id, buddy_id)
);
INSERT INTO study_buddies VALUES
(103, 102, '2025-09-02'),
(102, 101, '2025-01-13');
SELECT * FROM study_buddies ORDER BY student_id;CREATE TABLE
INSERT 0 2
student_id | buddy_id | since
------------+----------+------------
102 | 101 | 2025-01-13
103 | 102 | 2025-09-02
(2 rows)Inserting (103, 102, ...) a second time would be refused by study_buddies_pkey, while (103, 101, ...) would be accepted, because only the pair must be unique.
Key Takeaways
| You want to | Write |
|---|---|
| A primary key | student_id INTEGER PRIMARY KEY |
| A composite key | PRIMARY KEY (student_id, course_id) |
| No duplicate emails | email VARCHAR(80) UNIQUE |
| Add uniqueness later | ALTER TABLE students ADD CONSTRAINT students_phone_key UNIQUE (phone); |
| At most one NULL (PostgreSQL 15+) | UNIQUE NULLS NOT DISTINCT |
Was this tutorial helpful?