Database Integer and UUID Primary Keys
What you will learn
- How auto-numbered integer keys and UUID keys differ
- What an integer key reveals and why that can matter
- Why merging two databases is easy with UUIDs and painful with integers
- The costs of UUIDs
- A simple rule for choosing
Lesson 2.5 introduced surrogate keys, keys with no meaning that exist only to identify a row. This lesson compares the two most common kinds. It runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top) and creates a few small tables of its own in your browser's copy; Reset data removes them again. The examples build on each other, so run them from top to bottom.
1. Integer keys
The usual surrogate key is a whole number that the database assigns itself (INTEGER PRIMARY KEY in SQLite; other systems have their own spellings, so check the documentation of the system you use).
CREATE TABLE a_orders (id INTEGER PRIMARY KEY, item TEXT);
INSERT INTO a_orders (item) VALUES ('tea'), ('rice'), ('salt');
SELECT * FROM a_orders;
id item
-- ----
1 tea
2 rice
3 salt
(3 rows)
CREATE TABLE a_tickets (id INTEGER PRIMARY KEY, topic TEXT);
INSERT INTO a_tickets (topic) VALUES ('card lost'), ('address change'), ('limit raised');
SELECT * FROM a_tickets;
id topic
-- --------------
1 card lost
2 address change
3 limit raised
(3 rows)
CREATE TABLE a_notes (id INTEGER PRIMARY KEY, title TEXT);
INSERT INTO a_notes (title) VALUES ('homework'), ('school trip'), ('exam dates');
SELECT * FROM a_notes;
id title
-- -----------
1 homework
2 school trip
3 exam dates
(3 rows)
Integers are small, easy to read aloud ("order 3") and fast to compare. Two weaknesses:
- They can be guessed. If a web address ends in
/orders/3, a visitor can try/orders/4. The key does not make this unsafe by itself (permission checks do, lesson 8.4), but it makes guessing easy and it reveals how many rows exist. - Only one database numbers them. Two separate databases both start at 1.
Quick check: Why can an auto-numbered integer id leak information that a random UUID does not?
Integers count up in order, so an outsider who sees id = 1042 can guess that other rows exist near it and roughly how many there are. A random UUID reveals neither.
2. UUID keys
A UUID (universally unique identifier) is a 128-bit number, normally written as 36 characters such as 3f2b8c1e-.... A random UUID is generated by the application, with no central counter, and the chance of two being equal is so small that programs treat them as unique.
Python has the real thing in its uuid module (the ids change on every run, so only their shape is printed):
import uuid
ids = [str(uuid.uuid4()) for _ in range(3)]
print(len(ids), {len(i) for i in ids})
print(len(set(ids)))
3 {36}
3
All three ids are 36 characters long and all three are different. SQLite has no UUID function, but it can make something very close: randomblob(16) gives 16 random bytes and hex() writes them as 32 characters. The column below fills itself with such a value when no id is given. (A real UUID is written with dashes and has a few fixed bits that mark its version, so this is "UUID-like".)
CREATE TABLE b_orders (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), item TEXT);
INSERT INTO b_orders (item) VALUES ('tea'), ('rice'), ('salt');
SELECT COUNT(*) AS rows, COUNT(DISTINCT id) AS different_ids, MIN(length(id)) AS shortest, MAX(length(id)) AS longest FROM b_orders;
rows different_ids shortest longest
---- ------------- -------- -------
3 3 32 32
(1 row)
CREATE TABLE b_tickets (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), topic TEXT);
INSERT INTO b_tickets (topic) VALUES ('card lost'), ('address change'), ('limit raised');
SELECT COUNT(*) AS rows, COUNT(DISTINCT id) AS different_ids, MIN(length(id)) AS shortest, MAX(length(id)) AS longest FROM b_tickets;
rows different_ids shortest longest
---- ------------- -------- -------
3 3 32 32
(1 row)
CREATE TABLE b_notes (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), title TEXT);
INSERT INTO b_notes (title) VALUES ('homework'), ('school trip'), ('exam dates');
SELECT COUNT(*) AS rows, COUNT(DISTINCT id) AS different_ids, MIN(length(id)) AS shortest, MAX(length(id)) AS longest FROM b_notes;
rows different_ids shortest longest
---- ------------- -------- -------
3 3 32 32
(1 row)
Three rows, three different ids, all the same length. The values themselves differ on every run, so they are not printed.
3. Merging two databases
Imagine two places, each with its own database, joined into one later. Each starts numbering at 1, so each has a row 1 and a row 2. First with integer keys: copy the first database into a merged table, then try to add the second.
Two shops, each with its own orders:
CREATE TABLE shop_a_orders (id INTEGER PRIMARY KEY, item TEXT);
INSERT INTO shop_a_orders (item) VALUES ('tea'), ('rice'), ('salt');
CREATE TABLE shop_b_orders (id INTEGER PRIMARY KEY, item TEXT);
INSERT INTO shop_b_orders (item) VALUES ('soap'), ('oil');
CREATE TABLE merged_orders (id INTEGER PRIMARY KEY, item TEXT);
INSERT INTO merged_orders SELECT id, item FROM shop_a_orders;
(3 rows changed)
INSERT INTO merged_orders SELECT id, item FROM shop_b_orders;
IntegrityError: UNIQUE constraint failed: merged_orders.id
Two branches, each with its own tickets:
CREATE TABLE branch_a_tickets (id INTEGER PRIMARY KEY, topic TEXT);
INSERT INTO branch_a_tickets (topic) VALUES ('card lost'), ('address change'), ('limit raised');
CREATE TABLE branch_b_tickets (id INTEGER PRIMARY KEY, topic TEXT);
INSERT INTO branch_b_tickets (topic) VALUES ('new account'), ('loan question');
CREATE TABLE merged_tickets (id INTEGER PRIMARY KEY, topic TEXT);
INSERT INTO merged_tickets SELECT id, topic FROM branch_a_tickets;
(3 rows changed)
INSERT INTO merged_tickets SELECT id, topic FROM branch_b_tickets;
IntegrityError: UNIQUE constraint failed: merged_tickets.id
Two campuses, each with its own notes:
CREATE TABLE campus_a_notes (id INTEGER PRIMARY KEY, title TEXT);
INSERT INTO campus_a_notes (title) VALUES ('homework'), ('school trip'), ('exam dates');
CREATE TABLE campus_b_notes (id INTEGER PRIMARY KEY, title TEXT);
INSERT INTO campus_b_notes (title) VALUES ('sports day'), ('library hours');
CREATE TABLE merged_notes (id INTEGER PRIMARY KEY, title TEXT);
INSERT INTO merged_notes SELECT id, title FROM campus_a_notes;
(3 rows changed)
INSERT INTO merged_notes SELECT id, title FROM campus_b_notes;
IntegrityError: UNIQUE constraint failed: merged_notes.id
Row 1 of the second database has the same id as row 1 of the first, so the primary key refuses it. With integers, id 1 exists twice and every foreign key pointing at it becomes ambiguous; you must renumber and fix every reference. Now the same merge with random ids:
CREATE TABLE u_a_orders (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), item TEXT);
INSERT INTO u_a_orders (item) VALUES ('tea'), ('rice'), ('salt');
CREATE TABLE u_b_orders (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), item TEXT);
INSERT INTO u_b_orders (item) VALUES ('soap'), ('oil');
CREATE TABLE u_merged_orders (id TEXT PRIMARY KEY, item TEXT);
INSERT INTO u_merged_orders SELECT id, item FROM u_a_orders;
INSERT INTO u_merged_orders SELECT id, item FROM u_b_orders;
SELECT COUNT(*) AS merged_rows FROM u_merged_orders;
merged_rows
-----------
5
(1 row)
CREATE TABLE u_a_tickets (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), topic TEXT);
INSERT INTO u_a_tickets (topic) VALUES ('card lost'), ('address change'), ('limit raised');
CREATE TABLE u_b_tickets (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), topic TEXT);
INSERT INTO u_b_tickets (topic) VALUES ('new account'), ('loan question');
CREATE TABLE u_merged_tickets (id TEXT PRIMARY KEY, topic TEXT);
INSERT INTO u_merged_tickets SELECT id, topic FROM u_a_tickets;
INSERT INTO u_merged_tickets SELECT id, topic FROM u_b_tickets;
SELECT COUNT(*) AS merged_rows FROM u_merged_tickets;
merged_rows
-----------
5
(1 row)
CREATE TABLE u_a_notes (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), title TEXT);
INSERT INTO u_a_notes (title) VALUES ('homework'), ('school trip'), ('exam dates');
CREATE TABLE u_b_notes (id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), title TEXT);
INSERT INTO u_b_notes (title) VALUES ('sports day'), ('library hours');
CREATE TABLE u_merged_notes (id TEXT PRIMARY KEY, title TEXT);
INSERT INTO u_merged_notes SELECT id, title FROM u_a_notes;
INSERT INTO u_merged_notes SELECT id, title FROM u_b_notes;
SELECT COUNT(*) AS merged_rows FROM u_merged_notes;
merged_rows
-----------
5
(1 row)
All five rows arrive, with no clash and no renumbering: the rows can simply be copied. The same idea helps when an app creates records offline (a phone app, say) and sends them later: the app can invent the key itself without asking the server.
4. The costs of UUIDs
- Size. A UUID is 16 bytes as a number but 36 characters as text. Stored as text in SQLite it takes more space than a small integer, and every foreign key and index repeats it.
SELECT typeof(id) AS key_type, length(id) AS key_length FROM a_orders LIMIT 1;
SELECT typeof(id) AS key_type, length(id) AS key_length FROM b_orders LIMIT 1;
key_type key_length
-------- ----------
integer 1
(1 row)
key_type key_length
-------- ----------
text 32
(1 row)
SELECT typeof(id) AS key_type, length(id) AS key_length FROM a_tickets LIMIT 1;
SELECT typeof(id) AS key_type, length(id) AS key_length FROM b_tickets LIMIT 1;
key_type key_length
-------- ----------
integer 1
(1 row)
key_type key_length
-------- ----------
text 32
(1 row)
SELECT typeof(id) AS key_type, length(id) AS key_length FROM a_notes LIMIT 1;
SELECT typeof(id) AS key_type, length(id) AS key_length FROM b_notes LIMIT 1;
key_type key_length
-------- ----------
integer 1
(1 row)
key_type key_length
-------- ----------
text 32
(1 row)
The first row of each pair is the integer key (length counts the characters of the number written out, so 1 for the id 1: the database stores it in just a few bytes). The second is the text key: 32 characters (36 with dashes). As raw bytes a UUID would be 16:
import uuid
print(len(uuid.uuid4().bytes))
16
- Unfriendly. Nobody can say or type a UUID. Customers still need a short human code (an order number), which can live in a separate column.
- Random order. New random keys land all over an index instead of at the end, which can make inserts slower on large tables. How much depends on the system. Time-ordered UUID versions exist to reduce this; check what your system and language support.
- Some systems store UUIDs natively in a compact form; SQLite does not, so a UUID is just text or a 16-byte blob here. Check your own system's documentation.
Worked example: choosing for a tailor shop app
The shop has one database, staff use a website, and customers get an order number on a paper slip.
| Question | Answer | Leans toward |
|---|---|---|
| Several databases to merge? | no | integer |
| Records created offline? | no | integer |
| Keys appear in public web addresses? | yes, /orders/... |
UUID (or an integer plus a public random code) |
| People read keys aloud? | yes, the slip number | integer (or a separate short code) |
A good answer: integer primary key inside the database, plus a separate public_code column (random, unique) used in addresses. Names and shop are made up.
Common mistakes
- Thinking a UUID replaces permission checks. A hard-to-guess address is not security; always check who is asking.
- Making the UUID the only key you ever show people. Keep a short human code for slips, emails and phone calls.
- Storing a UUID inconsistently (sometimes with dashes, sometimes without, sometimes upper case). Pick one form.
- Using UUIDs everywhere "just in case" for a tiny single-database app that never needs them.
Key takeaways
- Integer keys are small, readable and fast, but guessable and unique only within one database.
- UUID keys can be made anywhere without coordination and merge cleanly, but are larger, unreadable and arrive in random order.
- Neither is a security feature.
- A common design: integer primary key plus a separate random public code.
- Choose by need: merging, offline creation, public addresses, human use.
Practice
1. Why do two databases that each use 1, 2, 3 as ids clash when merged?
Show answer
The same id then names different rows, so references to it become ambiguous.
2. Give two disadvantages of UUID keys.
Show answer
They are larger than small integers and unreadable for people; random ones also insert in random index order.
3. A web address contains /invoices/17. What risk does this show, and what is the real protection?
Show answer
Anyone can try 18, 19, and so on, and the number reveals how many invoices exist. The real protection is checking permissions on every request (lesson 8.4).
4. A mobile app saves notes offline and syncs later. Which key type is easier, and why?
Show answer
UUIDs, because the app can generate unique keys itself without asking the server.
5. Explain the design "integer primary key plus public code".
Show answer
The integer is the compact internal key used in joins and foreign keys; the random public code is the identifier shown in web addresses and messages, so internal numbers are not exposed.
6. Which would you pick for a classroom exercise database with one file and 20 rows, and why?
Show answer
Integer keys: nothing needs merging, offline creation or hiding, and they are the simplest.