Keys & Identity
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_name | city | joined_on |
|---|---|---|
| Maya Chen | Austin | 2024-03-11 |
| Maya Chen | Austin | 2025-08-02 |
| Dev Patel | Leeds | 2024-06-30 |
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_name | city | joined_on |
|---|---|---|
| Maya Chen | Austin | 2024-03-11 |
| Maya Chen | Austin | 2025-08-02 |
| Dev Patel | Leeds | 2024-06-30 |
| Dev Patel | Leeds | 2024-06-30 |
Description and identity
Give each person a user_id at signup and the same 4 rows look like this.
| user_id | full_name | city | joined_on |
|---|---|---|---|
| 41 | Maya Chen | Austin | 2024-03-11 |
| 42 | Maya Chen | Austin | 2025-08-02 |
| 43 | Dev Patel | Leeds | 2024-06-30 |
| 43 | Dev Patel | Leeds | 2024-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
| full_name | city | row_count |
|---|---|---|
| Maya Chen | Austin | 2 |
| Dev Patel | Leeds | 2 |
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.
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?
One key, chosen on purpose
- 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.
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.
| Column | Unique | Always present | Stable | Verdict |
|---|---|---|---|---|
| full_name | No, 2 Maya Chens | Yes | No, names change | Fails |
| Yes today | Yes | No, people switch providers | Fails on stability | |
| phone | Yes today | No, optional at signup | No, carriers reassign numbers | Fails |
| username | Yes | Yes | No, users rename themselves | Fails on stability |
| user_id | Yes | Yes | Yes, it has no reason to change | Passes |
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.
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.
- ▸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
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_rows | non_null_ids | distinct_ids | Reading |
|---|---|---|---|
| 120,400 | 120,400 | 120,400 | Unique and present |
| 120,400 | 120,400 | 120,388 | 12 rows repeat an existing ID |
| 120,400 | 120,395 | 120,395 | 5 rows have no ID |
- 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.
- 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.
Lumen starts selling prints and needs a primary key for print_orders. Which choice keeps all 3 promises?
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.
| user_id | username |
|---|---|
| 41 | maya.chen |
| 42 | mayachen_atx |
| 43 | dev.patel |
| photo_id | user_id | caption |
|---|---|---|
| 9001 | 41 | Lake at dawn |
| 9002 | 43 | Leeds market |
| 9003 | 41 | Trail dog |
| 9004 | 42 | Taco truck |
| 9005 | 57 | Night 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.
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.
| photo_id | user_id |
|---|---|
| 9005 | 57 |
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.
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.
- The foreign key matches 0 rows
- An inner join drops the row
- Counts come out too low
- The foreign key matches 2 or more rows
- The join repeats the row
- Counts and sums come out too high
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?
When no single column is enough
Lumen adds likes. Each row of likes records that one user liked one photo.
| user_id | photo_id | liked_at |
|---|---|---|
| 41 | 9002 | 2026-02-01 09:14 |
| 41 | 9004 | 2026-02-01 09:15 |
| 43 | 9001 | 2026-02-01 10:02 |
| 42 | 9001 | 2026-02-02 18:40 |
| 43 | 9003 | 2026-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.
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.
| Key | One row means | The table accepts |
|---|---|---|
| (user_id, photo_id) | A user likes a photo | One like per user per photo |
| (user_id, photo_id, liked_at) | A user liked a photo at a moment | The same user liking the same photo again a second later |
| (photo_id) | A photo has a like | One 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.
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
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.
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.
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?
Where a key value comes from
Natural keys
Auto-increment
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.
Time-ordered IDs
Choosing
| Strategy | Made by | Size | Sorted by creation | Breaks when |
|---|---|---|---|---|
| Natural | The outside world | Varies | No | The value changes or is reissued |
| Auto-increment | One database counter | 8 bytes | Yes | A second database starts counting |
| UUID version 4 | Any machine | 16 bytes | No | Storage size or readable IDs matter most |
| Time-ordered ID | Any machine with a clock | 8 or 16 bytes | Yes | A 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 has one database and a `users` table with no key yet. Each stage brings a new requirement.
| emailVARCHAR | usernameVARCHAR | joined_onDATE |
|---|
| photo_idBIGINTPK | captionVARCHAR | posted_atTIMESTAMP |
|---|
Launch week. `photos` must point at its poster, so `users` needs a primary key.
> 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.
orders.customer_id must be remapped together with the customers, or thousands of orders attach to the wrong person without any error.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
- 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
- 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
- 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.
- 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.
- 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