Choosing Keys

Updated · 7 min read
mediumPostgreSQL 18sqlprimary-keysurrogate-keynatural-keyuuiddesigninterview

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 UNIQUE on 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 keySurrogate key
Exampleemail, (city, state)student_id, payment_id
MeaningComes from the real worldMeans nothing outside the database
Can change?Yes: people change emailsNo reason to ever change
Always present?Not always: Navika has no emailAlways: the database assigns it
Readable in queriesYesNo; 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.

student_id never changes; email may change or be missing, so it gets UNIQUE instead of being the key

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

SQL▶ Try it
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;
Output
 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 identityUUID
Size4 / 8 bytes16 bytes
Generated byThe database, in orderAnyone, anywhere (apps, offline devices)
RevealsHow many rows exist; easy to guess the next idNothing; hard to guess
Index localityExcellent (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.

SQL▶ Try it
SELECT uuid_extract_version(gen_random_uuid()) AS random_version,
       uuid_extract_version(uuidv7()) AS time_ordered_version;
Output
 random_version | time_ordered_version
----------------+----------------------
              4 |                    7
(1 row)
A 4-byte integer that counts up versus a 16-byte UUID that can be made anywhere

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.

Natural Key or Surrogate?

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
SQL▶ Try it
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;
Output
 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).

Quick check: Choosing keys

3 questions
1Why isn't email a good primary key for students?
2How big is a UUID in PostgreSQL?
3Which key does enrollments use?

Key Takeaways

You wantUse
The default keyid INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
Ids made outside the databaseid UUID DEFAULT uuidv7() PRIMARY KEY
A junction tablePRIMARY KEY (student_id, course_id)
No duplicate emailsemail ... UNIQUE alongside the surrogate key

Was this tutorial helpful?

Lesson 74 of 115