Choosing Keys
Choosing a key in SQL means deciding which column, or columns, will identify each row of a table and be referenced by other tables. It is one of the few design decisions that is very hard to change later, because every foreign key, index and program that refers to a row depends on it. UNIQUE and PRIMARY KEY showed what a key is; this lesson is about choosing well. We will compare natural and surrogate keys, integers and UUIDs, and composite keys, and see why the most important property of a key is that it never changes.
In One Minute
- A natural key comes from real data (an email, a state code); a surrogate key is made up (
student_id). - Surrogate keys never need to change, so most tables use them, with
UNIQUEon natural values. - Integers are small and fast; UUIDs can be generated anywhere without coordination.
- Composite keys fit junction tables, like
(student_id, course_id). - Whatever you choose: unique, always present, and never changing.
Natural vs Surrogate Keys
| Natural key | Surrogate key | |
|---|---|---|
| Example | email, (city, state) | student_id, payment_id |
| Meaning | Comes from the real world | Means nothing outside the database |
| Can change? | Yes: people change emails | No reason to ever change |
| Always present? | Not always: Navika has no email | Always: the database assigns it |
| Readable in queries | Yes | No; needs a join to show names |
The Fee Tracker uses both. Students, courses and payments have surrogate keys, because names and emails change or are missing. Cities use the natural key (city, state), because a city's name and state are stable, always present and unique together.
Integers vs UUIDs
A UUID is a 128-bit identifier that can be generated anywhere with practically no chance of a duplicate. PostgreSQL generates them with gen_random_uuid() (random, version 4) and, from PostgreSQL 18, uuidv7() (time-ordered, version 7):
SELECT pg_typeof(gen_random_uuid()) AS type,
length(gen_random_uuid()::text) AS characters_as_text,
pg_column_size(gen_random_uuid()) AS uuid_bytes,
pg_column_size(1::integer) AS integer_bytes,
pg_column_size(1::bigint) AS bigint_bytes; type | characters_as_text | uuid_bytes | integer_bytes | bigint_bytes
------+--------------------+------------+---------------+--------------
uuid | 36 | 16 | 4 | 8
(1 row)Explanation: A UUID is 16 bytes, four times an INTEGER. Its value differs on every run, so this example shows its size rather than the value itself. The two kinds compare like this:
INTEGER / BIGINT identity | UUID | |
|---|---|---|
| Size | 4 / 8 bytes | 16 bytes |
| Generated by | The database, in order | Anyone, anywhere (apps, offline devices) |
| Reveals | How many rows exist; easy to guess the next id | Nothing; hard to guess |
| Index locality | Excellent (always increasing) | Random v4: poor; time-ordered v7: good |
Use identity integers by default. Choose UUIDs when ids must be created outside the database, merged across systems, or must not reveal counts or be guessable in URLs; prefer uuidv7() so new rows still land at the end of the index.
SELECT uuid_extract_version(gen_random_uuid()) AS random_version,
uuid_extract_version(uuidv7()) AS time_ordered_version; random_version | time_ordered_version
----------------+----------------------
4 | 7
(1 row)Composite Keys
A composite key fits a table whose rows are identified by a combination, most often a junction table. enrollments uses (student_id, course_id): the pair is unique, always present, and never changes, and it also stops a student enrolling twice in the same course. The cost is that tables referencing it need both columns, as payments does. If many tables would reference a junction table, give it a surrogate key and keep UNIQUE (student_id, course_id) instead.
Common Mistakes
Using an email or name as the key. It changes or is missing. Use a surrogate key plus UNIQUE.
Surrogate keys with no unique natural constraint. Duplicate students with different ids slip in.
Random UUIDs on huge, insert-heavy tables. Inserts scatter across the index. Use uuidv7() or integers.
Exposing sequential ids in public URLs. Anyone can guess /payments/8. Check permissions, or use UUIDs.
Interview Corner
What's the difference between a natural key and a surrogate key?
A natural key is a real-world value that identifies a row, such as an email; a surrogate key is an artificial identifier, such as an identity integer, with no meaning outside the database.
When would you use a UUID as a primary key?
When ids must be generated outside the database or across systems without coordination, or must not reveal row counts. Time-ordered UUIDs (v7) keep index inserts efficient.
What makes a good primary key?
It's unique, never NULL, never changes, and is compact enough to index and reference efficiently.
Practice
Challenge: List the primary key column(s) of each Fee Tracker table, to see which are surrogate and which natural or composite. Use information_schema.key_column_usage joined to table_constraints.
Show solution
SELECT kcu.table_name, kcu.column_name, kcu.ordinal_position
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON kcu.constraint_name = tc.constraint_name
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = 'public'
ORDER BY kcu.table_name, kcu.ordinal_position; table_name | column_name | ordinal_position
-------------+-------------+------------------
cities | city | 1
cities | state | 2
courses | course_id | 1
enrollments | student_id | 1
enrollments | course_id | 2
payments | payment_id | 1
students | student_id | 1
(7 rows)courses, payments and students use single surrogate columns. cities uses the natural pair (city, state), and enrollments the composite pair (student_id, course_id).
Key Takeaways
| You want | Use |
|---|---|
| The default key | id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY |
| Ids made outside the database | id UUID DEFAULT uuidv7() PRIMARY KEY |
| A junction table | PRIMARY KEY (student_id, course_id) |
| No duplicate emails | email ... UNIQUE alongside the surrogate key |
Was this tutorial helpful?