IntermediateData Modeling · 22 min · 10 challenges

Keys & Identity

Instagram's engineers once wrote that the app was taking in more than 25 photos and 90 likes every second, too much for one database. Splitting the data raised an awkward question: if several databases hand out photo IDs at the same moment, what stops 2 of them from issuing the same number? One clash, and a like for your friend's dog lands on a stranger's lunch.

The Problem of Identity

Daily Life
Interviews

One name, 2 accounts

Lumen is a small photo-sharing app, and its first users table was built in an afternoon. It stores the name and city from the signup form, plus the date each person joined.

full_namecityjoined_on
Maya ChenAustin2024-03-11
Maya ChenAustin2025-08-02
Dev PatelLeeds2024-06-30
A support ticket arrives: "Mayra Castillo in Austin has moved to Denver. Please update her profile." The table holds 2 rows that fit, and they belong to 2 different people who share a name and a city. Nothing in the ticket, and nothing in the table, says which row to change.
You could pin one row down by adding the join date to the filter. That works by luck. It holds only until 2 people named Mayra Castillo sign up in Austin on the same day, and nothing in the table prevents that.

A copy or a second person?

The nightly load that fills users fails partway through and is run again. The next morning the table has 4 rows.

full_namecityjoined_on
Maya ChenAustin2024-03-11
Maya ChenAustin2025-08-02
Dev PatelLeeds2024-06-30
Dev PatelLeeds2024-06-30
Did a second Dev Patel in Leeds join on the same day, or did the rerun write one person twice? The rows match on every column, so the table cannot say. Ask "how many users does Lumen have?" and you can defend either 3 or 4.
No filter can separate identical rows either. Any condition that matches one Dev row matches the other, so you can't delete the copy and keep the original.

Description and identity

Every column in that table describes a person. Descriptions repeat, because many people share a name or a city. They also change when someone moves or renames themselves. A column that describes can't be trusted to answer "which one?".
Identity is a separate job. A row has identity when some value appears in that row and in no other row of the table, for as long as the row exists. That value is called a key. With a key you can point at exactly one row, whether to read or change it or to refer to it from another table.

Give each person a user_id at signup and the same 4 rows look like this.

user_idfull_namecityjoined_on
41Maya ChenAustin2024-03-11
42Maya ChenAustin2025-08-02
43Dev PatelLeeds2024-06-30
43Dev PatelLeeds2024-06-30

Both problems now have answers. Support asks the customer for the number shown on her profile and updates user 42. The 2 Dev rows share user_id 43, so they are one person written twice and can be collapsed into a single row. A second Dev Patel would have received 44.

Asking the table directly

You can test whether a set of columns identifies rows. Group by those columns and keep the groups that hold more than one row.
SELECT
full_name,
city,
COUNT(*) AS row_count
FROM users
GROUP BY full_name, city
HAVING COUNT(*) > 1
full_namecityrow_count
Maya ChenAustin2
Dev PatelLeeds2

Each returned row is a group that these columns can't tell apart. An empty result means the columns separate every row the table holds today. Run it on user_id alone and only 43 comes back, the copy from the rerun, which is the one case you want caught.

Pipelines create this situation routinely. A retried load writes rows that resemble rows already present, and so does a file that arrives twice or a merge of sources. A key is what lets a pipeline tell "already here" from "new".
TIP
Practice on any table you work with: finish the sentence "one row is one ...". One user, one photo, one ticket. If the sentence won't finish, the table has no identity yet.
Multiple Choice

A support_tickets table has 3 columns: customer_name and subject, plus the opened_on date. Its nightly load failed halfway and was run again. The table now shows 2 identical rows: Dev Patel, Refund request, 2026-03-02. What can you conclude from the table alone?

The fix is always the same: decide what one row is, then give it a value that belongs to no other row.

Primary Keys: Data Identity

Daily Life
Interviews

One key, chosen on purpose

A table can hold several columns that happen to be unique. The primary key is the one the table officially uses as each row's identity: the value anyone uses to point at a row, whether from another table or from a query.
A primary key makes 3 promises
  • Unique. No 2 rows ever share a value.
  • Present. Every row has a value, so NULL (a missing value) is never allowed.
  • Stable. Once a row receives its value, that value stays for the life of the row.
The first 2 promises can be checked against data. The third is a claim about the future, and only knowledge of the business can back it.

Auditioning the columns

Lumen's signup form has grown, and users now has 5 columns that someone might propose as its primary key. Hold each one against the 3 promises.

ColumnUniqueAlways presentStableVerdict
full_nameNo, 2 Maya ChensYesNo, names changeFails
emailYes todayYesNo, people switch providersFails on stability
phoneYes todayNo, optional at signupNo, carriers reassign numbersFails
usernameYesYesNo, users rename themselvesFails on stability
user_idYesYesYes, it has no reason to changePasses

user_id passes because it means nothing. A value with meaning changes when the meaning changes: a new email provider, a new surname, a rebrand. A value that says only "this is row 42" has nothing to be wrong about, so nobody ever needs to edit it.

Stability has one more consequence: a key is never recycled. If user 42 deletes her account and the number is handed to a newcomer, every old log line and backup that mentions 42 now describes the wrong person.

Collisions come from the future

A collision is 2 different things receiving the same key value. Most collisions begin as a column that was unique in the data someone inspected. Suppose Lumen had keyed users on full name plus birth date. Among the first 5,000 signups that pair never repeats. A key also has to hold for signup number 5,000,001, and with millions of people a common name will meet its own birth date again.

The duplicate check from the previous section can prove a column unfit by returning a row. It cannot prove a column fit, because it sees only rows that exist. Choosing a primary key is reasoning about rows that have not arrived.
Questions for any proposed key
  • ▸Who assigns this value, and could they ever assign it twice?
  • ▸Can the real thing change this value and remain the same thing?
  • ▸Can a row exist before this value is known?
  • ▸Would it stay unique with 100x the rows, or a second source system?

Declared, then verified

users
user_idPKBIGINT
usernameVARCHAR
emailVARCHAR
phoneVARCHAR
full_nameVARCHAR
cityVARCHAR
joined_onDATE
In a diagram the primary key carries a PK badge. A transactional database, the kind that sits behind an app, enforces a declared key: a second insert of user 42 fails with an error. Many analytical warehouses, where data is gathered for reporting, only record the declaration. They enforce nothing, so a rerun load can write user 42 twice without complaint. There the promise is yours to verify after every load.
SELECT
COUNT(*) AS total_rows,
COUNT(user_id) AS non_null_ids,
COUNT(DISTINCT user_id) AS distinct_ids
FROM users

COUNT(*) counts rows. COUNT(user_id) skips NULLs, while COUNT(DISTINCT user_id) counts each value once. A healthy key returns the same number from all 3.

total_rowsnon_null_idsdistinct_idsReading
120,400120,400120,400Unique and present
120,400120,400120,38812 rows repeat an existing ID
120,400120,395120,3955 rows have no ID
✓Do
  • Say what one row is before choosing its key.
  • Prefer a key that carries no business meaning.
  • Run the 3-count check after every load.
✗Don't
  • Trust uniqueness seen in a sample of today's rows.
  • Put a value that users can edit into the key.
  • Hand the key of a deleted row to a new row.
Multiple Choice

Lumen starts selling prints and needs a primary key for print_orders. Which choice keeps all 3 promises?

A primary key gives one table a dependable way to name its rows. The payoff arrives when a second table needs to mention those rows.

Foreign Keys

Daily Life
Interviews

Pointing instead of copying

Lumen adds a photos table, and each photo has to say who posted it. One design copies the poster's username into every photo row. The day mayra.castillo renames herself mayac, each of her photo rows is wrong until a job rewrites them all.

The other design stores the poster's user_id. A foreign key is a column whose values are primary key values from another table. It stores the address of the user's row, and the facts about the user stay in users.

users
user_idPKBIGINT
usernameVARCHAR
emailVARCHAR
photos
photo_idPKBIGINT
user_idFKBIGINT
captionVARCHAR
posted_atTIMESTAMP
users
user_idusername
41maya.chen
42mayachen_atx
43dev.patel
photos
photo_iduser_idcaption
900141Lake at dawn
900243Leeds market
900341Trail dog
900442Taco truck
900557Night bus

Read photo 9003 the way a query does. Its user_id is 41, and row 41 of users holds the username mayra.castillo. The photo row never stored that name. A join looks it up each time someone asks.

SELECT
p.photo_id,
p.caption,
u.username
FROM photos AS p
JOIN users AS u
ON p.user_id = u.user_id

When user 41 becomes mayac, one row in users changes. Photos 9001 and 9003 show the new name on the next query, because 41 is all they ever stored. A stable primary key pays off here: everything pointing at it stays correct while the description around it changes.

Orphans

Photo 9005 points at user 57, and users has no row 57. A row whose foreign key matches nothing is called an orphan. Orphans appear in 3 common ways: a user row was deleted and its photos were left behind, the photos file was loaded before the users file, or a value was mistyped upstream.

The damage is quiet. The join above returns 4 rows, while photos holds 5. Photo 9005 finds no partner and leaves the result without an error. A dashboard built on that join reports 4 photos, and nobody is told that one is missing.

An orphan check keeps every photo and returns the ones whose lookup came back empty.
SELECT
p.photo_id,
p.user_id
FROM photos AS p
LEFT JOIN users AS u
ON p.user_id = u.user_id
WHERE u.user_id IS NULL
photo_iduser_id
900557

A transactional database with the foreign key declared refuses both mistakes by default. It rejects a photo that names user 57, and it blocks the deletion of a user who still has photos. The key can instead be declared to delete those photos along with the user, or to set their user_id to NULL. A warehouse that does not enforce the declaration accepts everything, so this query belongs after each load, next to the 3-count check on the primary key.

TIP
Load users before photos, and delete in the reverse order, so no photo ever points at a user that is absent.

Why the target must be unique

A foreign key should point at a column that is unique in the other table. Suppose photos stored full_name and the join matched on it. Lumen has 2 users named Mayra Castillo, so each of their photos matches 2 user rows and comes back twice. The 3 photos they posted return as 6 rows, which inflates any count or sum built on the join.

Target missing
  • The foreign key matches 0 rows
  • An inner join drops the row
  • Counts come out too low
Target duplicated
  • The foreign key matches 2 or more rows
  • The join repeats the row
  • Counts and sums come out too high
Neither failure raises an error. A join returns the right rows only when the target column holds every value the foreign key uses, and holds each of them once.
Multiple Choice

Suppose a larger photos table has 1,000 rows, and 30 of them carry a user_id that does not exist in users. user_id is unique in users. What value does this query return?

SELECT
COUNT(*) AS photo_count
FROM photos AS p
JOIN users AS u
ON p.user_id = u.user_id
A foreign key borrows a primary key value from another table. If the target column stays unique and every borrowed value has a match, joins return exactly the rows you expect.

Composite Keys

Daily Life
Interviews

When no single column is enough

Lumen adds likes. Each row of likes records that one user liked one photo.

user_idphoto_idliked_at
4190022026-02-01 09:14
4190042026-02-01 09:15
4390012026-02-01 10:02
4290012026-02-02 18:40
4390032026-02-03 07:55

Try each column as the key. user_id repeats, because user 41 liked 2 photos. photo_id repeats, because photo 9001 was liked twice. The pair behaves differently: (41, 9002) appears once, and so does every other pair. A primary key made of 2 or more columns is a composite key. Its uniqueness promise applies to the combination as a whole, so each column on its own is free to repeat.

users
user_idPKBIGINT
usernameVARCHAR
photos
photo_idPKBIGINT
user_idFKBIGINT
captionVARCHAR
likes
user_idPKBIGINT
photo_idPKBIGINT
liked_atTIMESTAMP

In the diagram both columns carry the PK badge. Each is also a foreign key: user_id points at users and photo_id points at photos, so a like can only join things that exist.

The key is a business rule

Choosing (user_id, photo_id) states something about the product: a user can like a photo once. A second like from user 41 on photo 9002 carries a pair that already exists, so it collides and is refused. The columns in the key decide what one row means and what the table will accept.

KeyOne row meansThe table accepts
(user_id, photo_id)A user likes a photoOne like per user per photo
(user_id, photo_id, liked_at)A user liked a photo at a momentThe same user liking the same photo again a second later
(photo_id)A photo has a likeOne like per photo, from anyone

The middle row is the trap of an oversized key. Adding liked_at still gives unique rows, yet a double tap now creates 2 valid likes and the photo's count is wrong. The last row is the opposite error: with too few columns the key rejects the second person who likes photo 9001. A good composite key holds the smallest set of columns that stays unique.

TIP
Say the key as a sentence that starts "one row per". likes is one row per user per photo. If that sentence sounds wrong to someone who knows the product, the key is wrong.

Checking a pair

SELECT
user_id,
photo_id,
COUNT(*) AS row_count
FROM likes
GROUP BY user_id, photo_id
HAVING COUNT(*) > 1

This is the duplicate check with both columns in the grouping, and an empty result is the goal. Grouping by user_id alone would return every user with more than one like. That result is correct and harmless, since user_id was never the whole key.

The cost of a wide key

A composite key travels. Any table that refers to a like must carry every column of the key. Lumen's like_notifications table records the alert sent to a photo's owner about one like. It carries the liker's user_id and the photo_id, which together point at one row of likes, and the owner is found through photos. That pair is a 2-column foreign key, and its join needs both conditions.

SELECT
n.sent_at,
l.liked_at
FROM like_notifications AS n
JOIN likes AS l
ON n.user_id = l.user_id
AND n.photo_id = l.photo_id
Leave out the second condition and each notification matches every like its user ever made. For a user with 300 likes, one notification becomes 300 rows.

When a 2-column key starts spreading into many tables, a common alternative gives each like its own generated like_id as the primary key and keeps a separate uniqueness rule on the pair. The single column is cheaper to reference, and the rule on the pair still blocks the double like. Skip that rule and duplicates walk in, because every new row arrives with a fresh ID.

Multiple Choice

Lumen's photo_tags table records which tags sit on which photos. A photo can carry many tags, a tag can sit on many photos, and one tag must never appear twice on the same photo. Which primary key enforces that?

A composite key makes the same promise as any primary key, spread across several columns. The next question is where the values in a key come from.

Key Generation Strategies

Daily Life
Interviews

Where a key value comes from

Settling on a single meaningless column leaves one question open: who produces the value? There are 3 common sources, and each one fails in a different place.
//

Natural keys

A natural key is a value that already exists outside your system: an email address, a country code, a product barcode. It costs nothing to generate and it reads well in query results. Its weakness is that someone else controls it. Emails change, phone numbers are reassigned, and a supplier can reissue a code. Natural keys suit small reference tables such as currencies or countries, where a standards body sets the codes and rarely changes them.
//

Auto-increment

An auto-increment key is a counter kept by the database: the first row gets 1, the next gets 2. As a 64-bit integer each value takes 8 bytes, and the values sort in insertion order, so new rows collect at the end of the table. The counter is also the weakness, because it lives in one database. Open a second database that counts from 1 and both will issue user 42 to different people. The numbers leak information as well: an order confirmation numbered 1,042 tells a competitor how many orders you have taken.
//

UUIDs

A UUID is a 128-bit value, usually written as 36 characters such as 3f2b8c1e-9a4d-4e7b-b1c6-0d5a7e2f9c41. The common version 4 fills 122 of those bits at random. Any process can mint one without asking anyone, even a batch job or an app on a phone. A clash is possible in principle, yet a 50% chance of even one needs about 2.7 quintillion UUIDs, roughly a billion every second for 85 years.

SELECT
UUID() AS photo_id
The price is size and order. A UUID takes 16 bytes in binary form, double a 64-bit integer, and more when stored as text. Random values arrive in no order, so each new key lands at a random place in the key's index, and in the table itself wherever rows are stored in key order. Inserts then touch scattered storage pages instead of the last one. Nobody can read one aloud over the phone either.

Time-ordered IDs

A fourth design borrows from the last 2. It puts a timestamp in the leading bits and something unique to the generator in the trailing bits. IDs made on different machines never clash, and they still sort by creation time. Instagram published the layout of its 64-bit IDs.
41 bits
millisecond timestamp
13 bits
shard ID
10 bits
auto-increment sequence
1,024
IDs per shard per millisecond
A shard is one slice of the data, stored separately from the others. Because the shard number sits inside the ID, different shards can generate IDs in the same millisecond and never produce the same value. Version 7 of the UUID standard applies the same idea at 128 bits, leading with a millisecond timestamp.

Choosing

StrategyMade bySizeSorted by creationBreaks when
NaturalThe outside worldVariesNoThe value changes or is reissued
Auto-incrementOne database counter8 bytesYesA second database starts counting
UUID version 4Any machine16 bytesNoStorage size or readable IDs matter most
Time-ordered IDAny machine with a clock8 or 16 bytesYesA generator's clock jumps backwards

Start from the last column and ask which failure you can live with. If everything lives in one database and the IDs stay internal at modest volume, auto-increment is the cheapest correct answer. Rows created in many places, or on a phone before they reach a server: UUIDs or time-ordered IDs. A short list fixed by a standard: the natural code. Whichever you pick, keep the natural value as an ordinary column with its own uniqueness rule, so email still can't repeat after it stops being the key.

Lumen's user key, year by yearStep 1
>

Lumen has one database and a `users` table with no key yet. Each stage brings a new requirement.

users
emailVARCHARusernameVARCHARjoined_onDATE
photos
photo_idBIGINTPKcaptionVARCHARposted_atTIMESTAMP

Launch week. `photos` must point at its poster, so `users` needs a primary key.

A key holds only while its promise matches how the business works, so recheck the promise whenever a new data source arrives or the business expands into a new region or product.
PUTTING IT ALL TOGETHER

> A concert ticketing company buys a smaller rival and must merge both customer databases into one warehouse. Each company numbered its customers with an auto-increment counter starting at 1, so customer 1,042 exists twice, with a different person behind each copy, and every order and seat assignment in both systems points at those IDs.

The problem of identity: after the merge, customer 1,042 names 2 people, so the number no longer answers "which one?".
Primary keys: each counter was unique inside its own database, and the uniqueness promise broke the moment a second source arrived.
Foreign keys: orders.customer_id must be remapped together with the customers, or thousands of orders attach to the wrong person without any error.
Composite keys: the pair (source_company, customer_id) is unique across both systems and works as the key during the migration.
Key generation: new customers receive IDs from one generator that both systems share, and email stays unique as an ordinary column to catch people who held accounts at both companies.
KEY TAKEAWAYS
Identity is a separate job from description: a key answers "which row?" and nothing else.
A primary key must be unique and present. It must also be stable, and that part is a promise about rows that haven't arrived yet.
A foreign key borrows another table's primary key. Orphans shrink join results, and duplicate targets inflate them.
A composite key is a business rule: the smallest set of columns that makes one row per thing.
Auto-increment needs one counter, UUIDs need none, natural keys depend on someone else, and time-ordered IDs give both order and independence in exchange for trusting a clock.

How a row gets a name that stays unique, stays put, and lets every other table find it.

Category
Data Modeling
Difficulty
intermediate
Duration
22 minutes
Challenges
10 hands-on challenges

Topics covered: The Problem of Identity, Primary Keys: Data Identity, Foreign Keys, Composite Keys, Key Generation Strategies

Lesson Sections

  1. The Problem of Identity

    One name, 2 accounts A support ticket arrives: "Mayra Castillo in Austin has moved to Denver. Please update her profile." The table holds 2 rows that fit, and they belong to 2 different people who share a name and a city. Nothing in the ticket, and nothing in the table, says which row to change. You could pin one row down by adding the join date to the filter. That works by luck. It holds only until 2 people named Mayra Castillo sign up in Austin on the same day, and nothing in the table prevent

  2. Primary Keys: Data Identity (concepts: Primary Keys, Surrogate Keys)

    One key, chosen on purpose A table can hold several columns that happen to be unique. The primary key is the one the table officially uses as each row's identity: the value anyone uses to point at a row, whether from another table or from a query. The first 2 promises can be checked against data. The third is a claim about the future, and only knowledge of the business can back it. Auditioning the columns Stability has one more consequence: a key is never recycled. If user 42 deletes her account

  3. Foreign Keys (concepts: Foreign Keys)

    Pointing instead of copying Orphans An orphan check keeps every photo and returns the ones whose lookup came back empty. Why the target must be unique Neither failure raises an error. A join returns the right rows only when the target column holds every value the foreign key uses, and holds each of them once. A foreign key borrows a primary key value from another table. If the target column stays unique and every borrowed value has a match, joins return exactly the rows you expect.

  4. Composite Keys (concepts: Composite Keys, Junction Tables)

    When no single column is enough The key is a business rule Checking a pair The cost of a wide key Leave out the second condition and each notification matches every like its user ever made. For a user with 300 likes, one notification becomes 300 rows. A composite key makes the same promise as any primary key, spread across several columns. The next question is where the values in a key come from.

  5. Key Generation Strategies (concepts: Key Generation)

    Where a key value comes from Settling on a single meaningless column leaves one question open: who produces the value? There are 3 common sources, and each one fails in a different place. Natural keys A natural key is a value that already exists outside your system: an email address, a country code, a product barcode. It costs nothing to generate and it reads well in query results. Its weakness is that someone else controls it. Emails change, phone numbers are reassigned, and a supplier can reis