UNIQUE and PRIMARY KEY

Updated · 9 min read
mediumPostgreSQL 18sqlprimary-keyuniquecomposite-keyconstraintsinterview

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

  • UNIQUE refuses a duplicate value in a column, but allows NULL, usually more than once.
  • PRIMARY KEY means UNIQUE plus NOT NULL: every row has a value, and no two share it.
  • A table has at most one primary key, but may have many UNIQUE columns.
  • 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:

SQL▶ Try it
UPDATE students
SET email = 'srihitha.anamaneni@example.com'
WHERE student_id = 102;
Output
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:

SQL▶ Try it
INSERT INTO students (student_id, first_name, last_name, city, state, grade, joined_on)
VALUES (103, 'Navika', 'Anamaneni', 'Dallas', 'TX', 7, '2025-09-02');
Output
ERROR:  duplicate key value violates unique constraint "students_pkey"
DETAIL:  Key (student_id)=(103) already exists.

And a student with no id at all:

SQL▶ Try it
INSERT INTO students (student_id, first_name, last_name, city, state, grade, joined_on)
VALUES (NULL, 'Navika', 'Anamaneni', 'Dallas', 'TX', 7, '2025-09-02');
Output
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.

A duplicate is refused by both; NULL is refused only by the primary key

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:

CandidateProblem as a key
emailAdvitha and Navika don't have one; people change emails
first_name, last_nameTwo people can share a name; names change
phoneMissing for Navika; numbers get reassigned
student_idUnique, 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):

SQL
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:

SQL▶ Try it
INSERT INTO enrollments VALUES (101, 1, '2026-01-05', 'active');
Output
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:

SQL▶ Try it
INSERT INTO enrollments VALUES (101, 6, '2026-01-05', 'active')
RETURNING *;
Output
 student_id | course_id | enrolled_on | status
------------+-----------+-------------+--------
        101 |         6 | 2026-01-05  | active
(1 row)
101 appears in several rows and course 1 in several rows, but the pair (101, 1) only once

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:

SQL▶ Try it
SELECT student_id, email
FROM students
ORDER BY student_id;
Output
 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:

SQL▶ Try it
CREATE TABLE contacts (
  email VARCHAR(80) UNIQUE NULLS NOT DISTINCT
);
 
INSERT INTO contacts VALUES (NULL), (NULL);
Output
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.

Two NULL emails don't clash; with NULLS NOT DISTINCT the second NULL is refused

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:

SQL▶ Try it
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'students'
ORDER BY indexname;
Output
     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
SQL▶ Try it
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;
Output
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.

Quick check: UNIQUE and PRIMARY KEY

3 questions
1Which constraint refuses NULL?
2enrollments has PRIMARY KEY (student_id, course_id). Which insert is refused?
3Why is student_id a better primary key than email?

Key Takeaways

You want toWrite
A primary keystudent_id INTEGER PRIMARY KEY
A composite keyPRIMARY KEY (student_id, course_id)
No duplicate emailsemail VARCHAR(80) UNIQUE
Add uniqueness laterALTER TABLE students ADD CONSTRAINT students_phone_key UNIQUE (phone);
At most one NULL (PostgreSQL 15+)UNIQUE NULLS NOT DISTINCT

Was this tutorial helpful?

Lesson 32 of 115