Duplicates and Keys
Define what makes a row unique, detect exact and near duplicates, choose which record survives, and avoid deleting real repeated events.
Welcome back!
Step 1 of 10Learn
Three Marias, one customer
A clothing retailer's CRM holds these three records:
| id | name | city | |
|---|---|---|---|
| 1041 | Maria Lopez | maria.lopez@mail.com | Austin |
| 2207 | María López | Maria.Lopez@mail.com | Austin |
| 3115 | M. Lopez | maria.lopez@mail.com | Austin, TX |
They are one person. Because of them, Maria receives three copies of every promotion, the company reports more customers than it has, her purchase history is split so she never reaches the loyalty tier she earned, and any analysis of "average spend per customer" is too low.
These are near duplicates: records of the same entity that are not character-for-character identical. Exact duplicates, where every field matches, are easy to find and usually come from a file being loaded twice or a faulty export. Near duplicates come from people: a customer signs up again with a different device, a clerk retypes a name with an accent, a system adds a trailing space.
Deduplication has two parts. First, decide what makes two rows the same: which fields, after which normalization. Second, decide what to keep: which record survives and which details are merged from the others. Both are design decisions, and both must be written down.
Step 2 of 10Learn
Keys: what makes a row unique
Every clean table should have a key: a column, or combination of columns, whose value identifies exactly one row.
- A primary key is the column the table promises is unique, such as order_id. If a profile shows duplicate primary key values, something upstream is broken.
- A natural key comes from the real world, such as an email address, a tax number or a product barcode. It is meaningful but can change or be entered inconsistently.
- A surrogate key is an arbitrary ID assigned by a system, like customer 1041. It is stable and unique within the system but says nothing about whether two records describe the same person, which is exactly how Maria got three of them.
- A composite key uses several columns together. In a daily sales table, store_id alone repeats every day and date repeats for every store, but the pair store_id plus date should appear once.
Before deduplicating, state the grain of the table in one sentence: "one row per order", "one row per customer per month", "one row per sensor reading". The grain tells you which key must be unique. If the stated grain is "one row per customer" and the key repeats, you have duplicates. If the grain is "one row per order", repeated customer IDs are perfectly normal.
Step 3 of 10Practice · Choose one
A table records the number of visitors at each museum branch for each day. Which key should be unique?
Step 4 of 10Learn
Which record survives?
Once you know which rows describe the same entity, you need survivorship rules: rules that decide which values end up in the single clean record.
Common rules:
- Most recent wins: keep the record with the latest update timestamp, on the theory that newer information is more accurate. Good for addresses and phone numbers.
- Most complete wins: keep the record with the fewest missing fields.
- Field-by-field merge: take each field from the best source, such as email from the most recent record, birth date from the oldest, and loyalty points summed across all.
- Trusted source wins: prefer the billing system over a web form, because billing details are verified.
Whatever you choose, keep a crosswalk: a small table mapping every old ID to the surviving ID (2207 → 1041, 3115 → 1041). Orders, support tickets and other tables still point to the old IDs, and without the crosswalk their history would be orphaned.
Finally, normalize before you compare. "Maria.Lopez@mail.com" and "maria.lopez@mail.com " differ only in case and a trailing space; after stripping and lowercasing, they match exactly. Most near duplicates turn into exact duplicates once the mechanical cleaning from the last module is applied.
Step 5 of 10Practice · Code challenge · Python
Write dedupe_latest(rows). Each row is a dict with "id", "email" and "updated" (an ISO date string such as "2025-03-01"). Two rows are the same customer if their emails match after stripping spaces and lowercasing. Keep only the most recently updated row for each customer and return the sorted list of the ids you kept.
dedupe_latest([{"id": 1, "email": "Ann@x.com", "updated": "2025-01-05"}, {"id": 2, "email": " ann@x.com", "updated": "2025-03-01"}, {"id": 3, "email": "bo@x.com", "updated": "2024-12-30"}])dedupe_latest([{"id": 7, "email": "a@b.co", "updated": "2025-06-01"}, {"id": 8, "email": "A@B.CO ", "updated": "2025-01-01"}])dedupe_latest([{"id": 4, "email": "z@z.z", "updated": "2023-01-01"}])
Step 6 of 10Note
Step 7 of 10Learn
Where duplicates come from, and how to count them
Knowing the source of duplicates tells you whether to fix the data or the process. Typical causes:
- Double loads: the same file or batch imported twice. Every field matches, often including load timestamps within seconds of each other.
- Appending overlapping extracts: January 1–31 plus January 25 to February 28 duplicates a week.
- Joins with non-unique keys: joining orders to a customer table that contains Maria three times turns each of her orders into three rows. You will study this in the joining lesson.
- Re-registration and retyping: people and clerks creating new records instead of finding old ones.
To measure duplicates on a key in SQL, group by the key and keep groups with more than one row:
SELECT email_key, COUNT(*) FROM customers GROUP BY email_key HAVING COUNT(*) > 1;
In Python, a collections.Counter over the key does the same. Report two numbers: how many keys are duplicated and how many extra rows they create. "312 customers appear more than once, creating 401 extra rows" is far more useful than "there are some duplicates".
Fixing the process is the real win. A unique constraint in the database or a "did you mean this account?" step at sign-up prevents tomorrow's duplicates.
Step 8 of 10Practice · Fill in the blanks
Fill in the blanks
In SQL, to list keys that appear more than once, you group by the key and filter the groups with ` COUNT(*) > 1`. You cannot use WHERE for this, because WHERE filters rows they are grouped.
Step 9 of 10Practice · What would you do?
What would you do?
A payments table shows two rows for customer 5521: both for $4.50 at the same café, one minute apart. Every column matches except the transaction_id, which is different. Should you remove one as a duplicate?
Step 10 of 10Practice · True or false
Removing rows where every column is identical is always safe.
Lesson complete!