Database Unique Keys and Candidate Keys
What you will learn
- What a UNIQUE constraint does
- What a candidate key, primary key and alternate key are
- A unique combination of columns
- How SQLite treats NULL in unique columns
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It uses real tables and a few small tables of its own in your browser's copy; run the examples from top to bottom, and press Reset data to start again.
1. UNIQUE
A UNIQUE constraint says: no two rows may have the same value in this column. The sample databases already use it. A new row that repeats an existing value is refused:
Every customer has a different email. Copy the email of customer 1 into a new row:
INSERT INTO customers (first_name, last_name, email, city, country, joined_on)
SELECT 'Another', 'Person', email, 'Dhaka', 'Bangladesh', '2026-01-01'
FROM customers WHERE customer_id = 1;
IntegrityError: UNIQUE constraint failed: customers.email
Every branch has a different name. Copy the name of branch 1 into a new row:
INSERT INTO branches (name, city)
SELECT name, 'Rome' FROM branches WHERE branch_id = 1;
IntegrityError: UNIQUE constraint failed: branches.name
Every course has a different code. Copy the code of course 1 into a new row:
INSERT INTO courses (code, title, department_id, credits)
SELECT code, 'Another course', 1, 3 FROM courses WHERE course_id = 1;
IntegrityError: UNIQUE constraint failed: courses.code
Now a table of your own, with an email that must be unique:
CREATE TABLE members (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
);
INSERT INTO members (email, name) VALUES ('rina@example.com', 'Rina');
(1 row changed)
INSERT INTO members (email, name) VALUES ('rina@example.com', 'Another Rina');
IntegrityError: UNIQUE constraint failed: members.email
SELECT * FROM members;
id email name
-- ---------------- ----
1 rina@example.com Rina
(1 row)
CREATE TABLE members (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
);
INSERT INTO members (email, name) VALUES ('rina@example.com', 'Rina');
(1 row changed)
INSERT INTO members (email, name) VALUES ('rina@example.com', 'Another Rina');
IntegrityError: UNIQUE constraint failed: members.email
SELECT * FROM members;
id email name
-- ---------------- ----
1 rina@example.com Rina
(1 row)
CREATE TABLE members (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
);
INSERT INTO members (email, name) VALUES ('rina@example.com', 'Rina');
(1 row changed)
INSERT INTO members (email, name) VALUES ('rina@example.com', 'Another Rina');
IntegrityError: UNIQUE constraint failed: members.email
SELECT * FROM members;
id email name
-- ---------------- ----
1 rina@example.com Rina
(1 row)
The example address ends with example.com, a name reserved for examples. Notice the difference from a primary key: a table may have only one primary key but many UNIQUE columns, and unique columns may be changed.
2. Candidate, primary and alternate keys
Imagine a table of people with an id, a roll_no and an email:
| id | roll_no | name | |
|---|---|---|---|
| 1 | 2026-001 | rina@example.com | Rina |
| 2 | 2026-002 | sam@example.com | Sam |
Which columns could identify a row? id, roll_no and email could each do it, because each is unique and never empty. These are the candidate keys: every column (or set of columns) that is unique and non-empty, and has no unnecessary extra columns.
- You choose one candidate key as the primary key, for example
id(lesson 2.5 explains why). - The others are alternate keys. You still protect them with
UNIQUE NOT NULL.
CREATE TABLE people (
id INTEGER PRIMARY KEY,
roll_no TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
);
INSERT INTO people (roll_no, email, name) VALUES ('2026-001', 'rina@example.com', 'Rina');
(1 row changed)
Each alternate key guards itself. Repeat the roll number, then repeat the email:
INSERT INTO people (roll_no, email, name) VALUES ('2026-001', 'other@example.com', 'X');
IntegrityError: UNIQUE constraint failed: people.roll_no
INSERT INTO people (roll_no, email, name) VALUES ('2026-009', 'rina@example.com', 'X');
IntegrityError: UNIQUE constraint failed: people.email
CREATE TABLE people (
id INTEGER PRIMARY KEY,
roll_no TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
);
INSERT INTO people (roll_no, email, name) VALUES ('2026-001', 'rina@example.com', 'Rina');
(1 row changed)
Each alternate key guards itself. Repeat the roll number, then repeat the email:
INSERT INTO people (roll_no, email, name) VALUES ('2026-001', 'other@example.com', 'X');
IntegrityError: UNIQUE constraint failed: people.roll_no
INSERT INTO people (roll_no, email, name) VALUES ('2026-009', 'rina@example.com', 'X');
IntegrityError: UNIQUE constraint failed: people.email
CREATE TABLE people (
id INTEGER PRIMARY KEY,
roll_no TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
);
INSERT INTO people (roll_no, email, name) VALUES ('2026-001', 'rina@example.com', 'Rina');
(1 row changed)
Each alternate key guards itself. Repeat the roll number, then repeat the email:
INSERT INTO people (roll_no, email, name) VALUES ('2026-001', 'other@example.com', 'X');
IntegrityError: UNIQUE constraint failed: people.roll_no
INSERT INTO people (roll_no, email, name) VALUES ('2026-009', 'rina@example.com', 'X');
IntegrityError: UNIQUE constraint failed: people.email
The error message names the column that broke the rule.
"Has no unnecessary extra columns" matters: (id, name) is unique too, but only because id already is. A set that can lose a column and still be unique is a superkey, not a candidate key.
3. Unique combinations
Sometimes only a combination must be unique.
In the Shop, an employee may work many days and many time slots, but not twice in the same slot of the same day:
CREATE TABLE shifts (
id INTEGER PRIMARY KEY,
employee_id INTEGER NOT NULL REFERENCES employees (employee_id),
day TEXT NOT NULL,
slot INTEGER NOT NULL,
UNIQUE (employee_id, day, slot)
);
INSERT INTO shifts (employee_id, day, slot) VALUES (1, 'Mon', 1), (1, 'Mon', 2), (2, 'Mon', 1);
(3 rows changed)
INSERT INTO shifts (employee_id, day, slot) VALUES (1, 'Mon', 1);
IntegrityError: UNIQUE constraint failed: shifts.employee_id, shifts.day, shifts.slot
In the Bank, a branch has one advice desk, and it may be booked on many days and in many slots, but not twice in the same slot of the same day:
CREATE TABLE desk_bookings (
id INTEGER PRIMARY KEY,
branch_id INTEGER NOT NULL REFERENCES branches (branch_id),
day TEXT NOT NULL,
slot INTEGER NOT NULL,
UNIQUE (branch_id, day, slot)
);
INSERT INTO desk_bookings (branch_id, day, slot) VALUES (1, 'Mon', 1), (1, 'Mon', 2), (2, 'Mon', 1);
(3 rows changed)
INSERT INTO desk_bookings (branch_id, day, slot) VALUES (1, 'Mon', 1);
IntegrityError: UNIQUE constraint failed: desk_bookings.branch_id, desk_bookings.day, desk_bookings.slot
In the School, a teacher may teach on many days and in many periods, but not twice in the same period of the same day:
CREATE TABLE timetable (
id INTEGER PRIMARY KEY,
teacher_id INTEGER NOT NULL REFERENCES teachers (teacher_id),
day TEXT NOT NULL,
period INTEGER NOT NULL,
UNIQUE (teacher_id, day, period)
);
INSERT INTO timetable (teacher_id, day, period) VALUES (1, 'Mon', 1), (1, 'Mon', 2), (2, 'Mon', 1);
(3 rows changed)
INSERT INTO timetable (teacher_id, day, period) VALUES (1, 'Mon', 1);
IntegrityError: UNIQUE constraint failed: timetable.teacher_id, timetable.day, timetable.period
The same person, day and slot each appear several times, but the combination of all three may appear only once. The trio is what must be unique, not each column alone.
4. UNIQUE and NULL
NULL means "unknown" (lesson 2.3), so two unknowns are not considered equal. In SQLite a UNIQUE column that allows NULL accepts many NULLs.
The phone of a customer may be missing. Make a small table of your own:
Not every bank customer has given a phone number. Make a small table of your own:
The email of a student may be missing, and students.email is UNIQUE. Make a small table of your own that behaves the same way:
CREATE TABLE contacts (id INTEGER PRIMARY KEY, phone TEXT UNIQUE);
INSERT INTO contacts (phone) VALUES (NULL);
INSERT INTO contacts (phone) VALUES (NULL);
INSERT INTO contacts (phone) VALUES ('0171');
(1 row changed)
INSERT INTO contacts (phone) VALUES ('0171');
IntegrityError: UNIQUE constraint failed: contacts.phone
SELECT * FROM contacts ORDER BY id;
id phone
-- -----
1 NULL
2 NULL
3 0171
(3 rows)
CREATE TABLE contacts (id INTEGER PRIMARY KEY, phone TEXT UNIQUE);
INSERT INTO contacts (phone) VALUES (NULL);
INSERT INTO contacts (phone) VALUES (NULL);
INSERT INTO contacts (phone) VALUES ('0171');
(1 row changed)
INSERT INTO contacts (phone) VALUES ('0171');
IntegrityError: UNIQUE constraint failed: contacts.phone
SELECT * FROM contacts ORDER BY id;
id phone
-- -----
1 NULL
2 NULL
3 0171
(3 rows)
CREATE TABLE contacts (id INTEGER PRIMARY KEY, phone TEXT UNIQUE);
INSERT INTO contacts (phone) VALUES (NULL);
INSERT INTO contacts (phone) VALUES (NULL);
INSERT INTO contacts (phone) VALUES ('0171');
(1 row changed)
INSERT INTO contacts (phone) VALUES ('0171');
IntegrityError: UNIQUE constraint failed: contacts.phone
SELECT * FROM contacts ORDER BY id;
id phone
-- -----
1 NULL
2 NULL
3 0171
(3 rows)
Two rows with no phone are accepted; two rows with the same phone are not. Whether other systems treat NULLs in unique columns the same way is a detail to check in their documentation. If a value must always exist, add NOT NULL.
Worked example: find the candidate keys
A table of library loans:
| loan_id | member_id | book_id | borrowed_on |
|---|---|---|---|
| 1 | 7 | 40 | 2026-03-01 |
| 2 | 7 | 41 | 2026-03-01 |
| 3 | 8 | 40 | 2026-03-02 |
loan_idis unique: a candidate key.member_idalone repeats (7 twice),book_idalone repeats (40 twice),borrowed_onalone repeats.(member_id, book_id)is unique in this sample, but a member could borrow the same book again later, so it is not safe as a key.(member_id, book_id, borrowed_on)would be safer but still fails if the book is borrowed twice in one day.
The honest answer: loan_id is the key, and we should not claim the others are keys because the sample looks unique. A key is a rule about all possible data, not about the rows you see today. The loans are made up.
5. Upper and lower case: collation
Does UNIQUE treat Rina@Example.com and rina@example.com as different? In SQLite, by default yes: text is compared exactly. How text is compared and sorted is called its collation. You can choose one for a column; NOCASE ignores upper/lower case for the letters A to Z:
CREATE TABLE u1 (email TEXT UNIQUE);
CREATE TABLE u2 (email TEXT UNIQUE COLLATE NOCASE);
INSERT INTO u1 VALUES ('Rina@Example.com');
INSERT INTO u1 VALUES ('rina@example.com');
INSERT INTO u2 VALUES ('Rina@Example.com');
SELECT * FROM u1 ORDER BY email;
email
----------------
Rina@Example.com
rina@example.com
(2 rows)
INSERT INTO u2 VALUES ('rina@example.com');
IntegrityError: UNIQUE constraint failed: u2.email
SELECT 'a' = 'A' AS plain_equal, 'a' = 'A' COLLATE NOCASE AS nocase_equal, 'Zed' < 'apple' AS plain_less, 'Zed' < 'apple' COLLATE NOCASE AS nocase_less;
plain_equal nocase_equal plain_less nocase_less
----------- ------------ ---------- -----------
0 1 1 0
(1 row)
CREATE TABLE u1 (email TEXT UNIQUE);
CREATE TABLE u2 (email TEXT UNIQUE COLLATE NOCASE);
INSERT INTO u1 VALUES ('Rina@Example.com');
INSERT INTO u1 VALUES ('rina@example.com');
INSERT INTO u2 VALUES ('Rina@Example.com');
SELECT * FROM u1 ORDER BY email;
email
----------------
Rina@Example.com
rina@example.com
(2 rows)
INSERT INTO u2 VALUES ('rina@example.com');
IntegrityError: UNIQUE constraint failed: u2.email
SELECT 'a' = 'A' AS plain_equal, 'a' = 'A' COLLATE NOCASE AS nocase_equal, 'Zed' < 'apple' AS plain_less, 'Zed' < 'apple' COLLATE NOCASE AS nocase_less;
plain_equal nocase_equal plain_less nocase_less
----------- ------------ ---------- -----------
0 1 1 0
(1 row)
CREATE TABLE u1 (email TEXT UNIQUE);
CREATE TABLE u2 (email TEXT UNIQUE COLLATE NOCASE);
INSERT INTO u1 VALUES ('Rina@Example.com');
INSERT INTO u1 VALUES ('rina@example.com');
INSERT INTO u2 VALUES ('Rina@Example.com');
SELECT * FROM u1 ORDER BY email;
email
----------------
Rina@Example.com
rina@example.com
(2 rows)
INSERT INTO u2 VALUES ('rina@example.com');
IntegrityError: UNIQUE constraint failed: u2.email
SELECT 'a' = 'A' AS plain_equal, 'a' = 'A' COLLATE NOCASE AS nocase_equal, 'Zed' < 'apple' AS plain_less, 'Zed' < 'apple' COLLATE NOCASE AS nocase_less;
plain_equal nocase_equal plain_less nocase_less
----------- ------------ ---------- -----------
0 1 1 0
(1 row)
u1 accepted both spellings; u2 refused the second. The last line shows the effect on comparison and sorting: by default 'a' = 'A' is false (0) and 'Zed' < 'apple' is true (1, capital letters sort first); with NOCASE it is the other way round. Other systems have their own collation rules and defaults (some ignore case by default, and accents and other alphabets add more rules), so check the documentation of the system you use. The safe habit is to decide on purpose: store emails in one case, or give the column a case-insensitive collation, so the same address cannot be registered twice.
Common mistakes
- Deciding a column is unique because today's data looks unique. Uniqueness is a rule you choose and enforce.
- Leaving duplicates possible in an alternate key (no
UNIQUE). - Assuming UNIQUE rejects repeated NULLs. In SQLite it does not.
- Making a column unique that should not be (names, cities).
Key takeaways
UNIQUEforbids repeated values; a table can have many unique columns but only one primary key.- A candidate key is a minimal set of columns that identifies rows; one becomes the primary key, the rest are alternate keys.
- Uniqueness can apply to a combination of columns.
- In SQLite, unique columns that allow NULL accept several NULLs.
- Keys are rules about all future data, not about the rows you can see.
Practice
1. How many primary keys can a table have? How many UNIQUE columns?
Show answer
One primary key; any number of UNIQUE columns.
2. What is an alternate key?
Show answer
A candidate key that was not chosen as the primary key, still kept unique with UNIQUE NOT NULL.
3. Why is (id, name) not a candidate key if id is already unique?
Show answer
It contains an unnecessary column (name); id alone is already enough.
4. In the contacts table, why were two NULL phones accepted?
Show answer
NULL means unknown, so two NULLs are not treated as equal duplicates in SQLite's unique check.
5. Write a UNIQUE rule so that a room can host only one class per day and period.
Show answer
UNIQUE (room, day, period)
6. Why is "all sample rows are different" not proof that a column is unique?
Show answer
Future rows may repeat the value. Uniqueness is a rule you enforce with a constraint, not an observation about current data.