Database Primary Keys
What you will learn
- What a primary key is and the two rules it enforces
- Why every table should have one
- How to declare it, and how auto-numbering works in SQLite
- What a composite primary key is
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It creates 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. The problem: telling rows apart
Two people can share a name, a city and a birth year. If you need to change one of them, how do you point at the right row? You need a value that is different for every row and never missing: a primary key (PK).
A primary key has two rules:
- Unique: no two rows have the same key.
- Not empty: the key is never NULL (lesson 2.3).
(SQLite has one historical exception: in an ordinary, non-INTEGER primary key column it allows NULLs unless you add NOT NULL. Always add NOT NULL to such keys. An INTEGER PRIMARY KEY column cannot be NULL.)
2. Declaring a primary key
Every table of the sample databases has one. Ask SQLite which columns are the key (pk is the position of the column in the key, 0 means not part of it):
SELECT name, type, pk FROM pragma_table_info('customers') WHERE pk > 0;
name type pk
----------- ------- --
customer_id INTEGER 1
(1 row)
SELECT name, type, pk FROM pragma_table_info('accounts') WHERE pk > 0;
name type pk
---------- ------- --
account_id INTEGER 1
(1 row)
SELECT name, type, pk FROM pragma_table_info('students') WHERE pk > 0;
name type pk
---------- ------- --
student_id INTEGER 1
(1 row)
Now make a table of your own with a key, and look at what it allows. Two people named Rina from Dhaka are fine, because their ids differ:
CREATE TABLE newsletter (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT);
INSERT INTO newsletter VALUES (1, 'Rina', 'Dhaka');
INSERT INTO newsletter VALUES (2, 'Rina', 'Dhaka');
SELECT * FROM newsletter;
id name city
-- ---- -----
1 Rina Dhaka
2 Rina Dhaka
(2 rows)
CREATE TABLE visitors (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT);
INSERT INTO visitors VALUES (1, 'Rina', 'Dhaka');
INSERT INTO visitors VALUES (2, 'Rina', 'Dhaka');
SELECT * FROM visitors;
id name city
-- ---- -----
1 Rina Dhaka
2 Rina Dhaka
(2 rows)
CREATE TABLE club_members (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT);
INSERT INTO club_members VALUES (1, 'Rina', 'Dhaka');
INSERT INTO club_members VALUES (2, 'Rina', 'Dhaka');
SELECT * FROM club_members;
id name city
-- ---- -----
1 Rina Dhaka
2 Rina Dhaka
(2 rows)
A second row with id 1 is refused:
INSERT INTO newsletter VALUES (1, 'Sam', 'Khulna');
IntegrityError: UNIQUE constraint failed: newsletter.id
INSERT INTO visitors VALUES (1, 'Sam', 'Khulna');
IntegrityError: UNIQUE constraint failed: visitors.id
INSERT INTO club_members VALUES (1, 'Sam', 'Khulna');
IntegrityError: UNIQUE constraint failed: club_members.id
The key protects you: whatever program inserts data, an id can never point at two rows.
With the key you can touch exactly one row:
UPDATE newsletter SET city = 'Sylhet' WHERE id = 2;
SELECT * FROM newsletter ORDER BY id;
id name city
-- ---- ------
1 Rina Dhaka
2 Rina Sylhet
(2 rows)
UPDATE visitors SET city = 'Sylhet' WHERE id = 2;
SELECT * FROM visitors ORDER BY id;
id name city
-- ---- ------
1 Rina Dhaka
2 Rina Sylhet
(2 rows)
UPDATE club_members SET city = 'Sylhet' WHERE id = 2;
SELECT * FROM club_members ORDER BY id;
id name city
-- ---- ------
1 Rina Dhaka
2 Rina Sylhet
(2 rows)
Filtering by name = 'Rina' would have changed both.
3. Auto-numbering
You usually let the database choose new ids. In SQLite, a column declared exactly INTEGER PRIMARY KEY fills itself with the next free number if you leave it out. last_insert_rowid() returns the id just assigned:
INSERT INTO newsletter (name, city) VALUES ('Lee', 'Khulna');
INSERT INTO newsletter (name, city) VALUES ('Amy', 'Dhaka');
SELECT last_insert_rowid() AS last_id;
SELECT id, name FROM newsletter ORDER BY id;
last_id
-------
4
(1 row)
id name
-- ----
1 Rina
2 Rina
3 Lee
4 Amy
(4 rows)
INSERT INTO visitors (name, city) VALUES ('Lee', 'Khulna');
INSERT INTO visitors (name, city) VALUES ('Amy', 'Dhaka');
SELECT last_insert_rowid() AS last_id;
SELECT id, name FROM visitors ORDER BY id;
last_id
-------
4
(1 row)
id name
-- ----
1 Rina
2 Rina
3 Lee
4 Amy
(4 rows)
INSERT INTO club_members (name, city) VALUES ('Lee', 'Khulna');
INSERT INTO club_members (name, city) VALUES ('Amy', 'Dhaka');
SELECT last_insert_rowid() AS last_id;
SELECT id, name FROM club_members ORDER BY id;
last_id
-------
4
(1 row)
id name
-- ----
1 Rina
2 Rina
3 Lee
4 Amy
(4 rows)
The last id is handy for linking rows (chapter 3). Other systems use other spellings for auto-numbering (for example AUTO_INCREMENT or identity columns). The idea is the same; read your system's documentation for the exact words.
Ids carry no meaning, and gaps are normal. With a plain INTEGER PRIMARY KEY, SQLite can hand out the number of a deleted last row again. Do not rely on numbers being never reused; if you need that, check the SQLite documentation for AUTOINCREMENT.
4. Composite primary keys
Sometimes no single column identifies a row, but a combination does. The sample databases have such tables.
In the Shop, an order has several lines. Line 1 appears in many orders and order 1 appears on many lines, but the pair (order_id, line_no) is unique:
SELECT name, pk FROM pragma_table_info('order_items') WHERE pk > 0 ORDER BY pk;
SELECT order_id, line_no, product_id FROM order_items WHERE order_id = 1 ORDER BY line_no;
name pk
-------- --
order_id 1
line_no 2
(2 rows)
order_id line_no product_id
-------- ------- ----------
1 1 13
1 2 27
1 3 26
1 4 30
(4 rows)
The same pair twice is refused:
INSERT INTO order_items VALUES (1, 1, 5, 1, 9.99);
IntegrityError: UNIQUE constraint failed: order_items.order_id, order_items.line_no
The Bank has no composite key, so make a table of your own: one interest rate per branch per day. A branch appears many times and a day appears many times, but the pair (branch_id, rate_date) is unique:
CREATE TABLE daily_rates (
branch_id INTEGER NOT NULL REFERENCES branches (branch_id),
rate_date TEXT NOT NULL,
rate REAL NOT NULL,
PRIMARY KEY (branch_id, rate_date)
);
INSERT INTO daily_rates VALUES (1, '2026-01-05', 2.5), (1, '2026-01-06', 2.5), (2, '2026-01-05', 2.4);
SELECT * FROM daily_rates ORDER BY branch_id, rate_date;
branch_id rate_date rate
--------- ---------- ----
1 2026-01-05 2.5
1 2026-01-06 2.5
2 2026-01-05 2.4
(3 rows)
The same pair twice is refused:
INSERT INTO daily_rates VALUES (1, '2026-01-05', 3.0);
IntegrityError: UNIQUE constraint failed: daily_rates.branch_id, daily_rates.rate_date
In the School, enrollments has one row per student per section. A student appears in many sections and a section holds many students, but the pair (student_id, section_id) is unique:
SELECT name, pk FROM pragma_table_info('enrollments') WHERE pk > 0 ORDER BY pk;
SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 ORDER BY section_id;
name pk
---------- --
student_id 1
section_id 2
(2 rows)
student_id section_id grade
---------- ---------- -----
1 19 NULL
1 30 49.2
1 41 60.8
(3 rows)
The same pair twice is refused:
INSERT INTO enrollments VALUES (1, 19, '2026-02-01', NULL);
IntegrityError: UNIQUE constraint failed: enrollments.student_id, enrollments.section_id
A student cannot be enrolled twice in the same section, and an order cannot have two line 1s.
5. Good primary keys
- Unique and never NULL (required).
- Stable: it never changes. Other tables will point to it (chapter 3).
- Short: small numbers are cheap to store and compare.
- Meaningless, usually: lesson 2.5 compares keys that carry meaning (like a national ID) with plain numbers.
Worked example: choose keys for three tables
| Table | One row is... | Key |
|---|---|---|
students |
one student | id (auto-number) |
courses |
one course | id (auto-number), or code such as MATH101 if codes never change |
enrolments |
one student in one course | composite (student_id, course_id) |
For enrolments the pair is the natural identity: a student is enrolled in a course or not. Two columns together, never repeated. The tables are made up.
Common mistakes
- No primary key. Duplicate rows creep in and you cannot update a single row safely.
- Using a name as the key. Names repeat and change.
- A key that can change (an email address, a phone number).
- Reusing or editing ids by hand. Let the database assign them and never renumber.
- Forgetting
NOT NULLon a non-integer key in SQLite.
Key takeaways
- A primary key identifies each row: unique and never NULL.
- Every table should have one.
INTEGER PRIMARY KEYauto-numbers in SQLite; other systems have their own syntax.- A composite key combines several columns when only the combination is unique.
- Choose keys that are stable and short.
Practice
1. What two rules does a primary key enforce?
Show answer
Values are unique, and never NULL.
2. Why is UPDATE students SET city = 'Sylhet' WHERE name = 'Rina' risky?
Show answer
Names are not unique, so it may change several students. Filter by the primary key instead.
3. What happens when you insert a row with a primary key value that already exists?
Show answer
The database refuses the insert with an integrity error (UNIQUE constraint failed).
4. A table attendance records whether each student came on each date. What would a composite key be?
Show answer
(student_id, date): one row per student per day.
5. Why should an email address not be a primary key?
Show answer
People change their email address, and a key should be stable because other tables refer to it. (It can still be made unique, lesson 2.6.)
6. What does last_insert_rowid() give you after an insert in SQLite?
Show answer
The id the database assigned to the row just inserted.