Deduplicating Rows Using Self Joins
Remove near-duplicates by pairing rows against a preferred survivor.
In plain words
Compare the table with itself, find rows that match, and keep only the first of each.
Think of it like…
Laying two copies of the same guest list side by side and drawing a line between any two entries that look like the same person, then crossing out the later entry of each pair.
Where you’ve seen it
A CRM import created duplicate contacts that differ only in case and spaces. A review query lists pairs: SELECT a.id AS duplicate_id, b.id AS survivor_id, a.email FROM contacts a JOIN contacts b ON lower(trim(b.email)) = lower(trim(a.email)) AND b.id < a.id; The team repoints the duplicates' activities to the survivor ids, deletes the duplicates, then adds a unique index on lower(trim(email)).
Words you’ll hear
- Survivor row
- The row you keep from each duplicate group, chosen by a clear rule.
- b.id < a.id
- Pairs each row only with older rows, so no row is paired with itself or twice.
- DELETE … USING / JOIN
- PostgreSQL and MySQL syntax for deleting based on a self-join.
- Near-duplicate
- Rows that match after normalising or fuzzy comparison, not exactly.
Visual diagram
Theory & example queries
Finding and deleting with a self-join
The join condition does two jobs: the matching columns define what counts as a duplicate, and b.id < a.id makes the pairing one-directional, so a row never matches itself and each pair appears once. Every row that appears as a has at least one older duplicate; the rows that never appear as a are the survivors.
PostgreSQL deletes with DELETE FROM contacts a USING contacts b WHERE lower(b.email) = lower(a.email) AND b.id < a.id; MySQL uses DELETE a FROM contacts a JOIN contacts b ON b.email = a.email AND b.id < a.id; Run the SELECT version first, inside a transaction, and check the count. To keep the newest row instead, flip the comparison to b.id > a.id.
| id | created_at | archived |
|---|---|---|
| 1 | 2024-11-20 | false |
| 2 | 2024-12-15 | false |
| 3 | 2026-01-05 | false |
DELETE FROM events a USING events bWHERE b.user_id = a.user_id AND b.event_type = a.event_type AND b.occurred_at = a.occurred_at AND b.id < a.id;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Illustrative PostgreSQL status for 12 rows with an older matching event ID retained.
Key takeaway: Match columns define a duplicate; b.id < a.id picks the survivor.
Near-duplicates, merging and limits
For near-duplicates, compare normalised values (lower(trim(email)), digits-only phone numbers) or use similarity: with pg_trgm, ON similarity(a.name, b.name) > 0.8 AND a.postcode = b.postcode AND b.id < a.id finds likely matches. An exact column such as postcode keeps the comparison from becoming every row against every row. Write fuzzy pairs into a review table instead of deleting them automatically.
Before deleting, move child rows to the survivor (UPDATE orders SET customer_id = p.survivor_id FROM pairs p WHERE orders.customer_id = p.duplicate_id), or foreign keys will block the delete or cascade it away. Self-joins create n·(n−1)/2 pairs per group of n, which is fine for pairs and triples but slow for groups of thousands; and choosing a survivor by "most recent activity" rather than lowest id is simpler with ROW_NUMBER.
SELECT a.id AS duplicate_id, MIN(b.id) AS survivor_idFROM contacts a JOIN contacts b ON lower(trim(b.email)) = lower(trim(a.email)) AND b.id < a.idGROUP BY a.id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| duplicate_id | survivor_id |
|---|---|
| 18 | 4 |
| 29 | 4 |
| 41 | 33 |
Note: Illustrative normalized-email duplicates; MIN(b.id) identifies the oldest surviving contact.
MIN(b.id) is the oldest row in the group.
Key takeaway: Normalise or fuzzy-match, merge children to the survivor, then delete.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Define what a duplicate is
Pick the matching columns and how to normalise them: exact email, lower-cased email, or name plus postcode.
lower(trim(email))
When to use it & trade-offs
What it is
A self-join pairs each row with other rows of the same table, which makes duplicates visible as pairs: FROM customers a JOIN customers b ON b.email = a.email AND b.id < a.id lists every row (a) that has an older twin (b). Turn the same join into a DELETE and every row with an older duplicate is removed, leaving the oldest row in each group as the survivor. Self-joins also handle near-duplicates, where two rows aren't identical but are close enough to be the same person.
Why it matters: Duplicate customers, contacts and products come from double form submissions, imports and integrations. Before deleting anything you usually need to review pairs, merge child records onto the survivor, and handle fuzzy matches, and self-joins are the natural tool for all three. It's also the classic interview answer for "delete duplicate rows keeping one".
When to reach for it
- Reviewing duplicate contacts before a merge
- Fuzzy matching people or companies
- Classic "delete duplicates, keep one" tasks
When to avoid or be careful
- Joining without b.id < a.id, which pairs rows with themselves
- Deleting before moving child records to the survivor
- Self-joins on groups with thousands of duplicates
Self-join vs ROW_NUMBER vs GROUP BY for deduplication
Strengths: Shows exactly which row duplicates which; supports similarity conditions.
Watch out: Pairs grow quadratically in large groups.
Strengths: One pass; survivor by any ORDER BY, like latest activity.
Watch out: Can't express fuzzy matching between rows.
Strengths: Short and portable.
Watch out: Only gives the survivor id, not the other columns.
Interview signals & numbers to know
When this topic comes up
- “Delete duplicate rows but keep one”
- “Merge duplicate customer records”
- “Emails differ only by case”
- Fuzzy matching
- Survivor selection
Benchmarks & rules of thumb
- n·(n−1)/2
- pairs in a duplicate group of n
- b.id < a.id
- keeps the oldest row
- 0.3
- pg_trgm's default threshold for the % similarity operator
Common mistakes & follow-ups
Common interview mistakes
- Joining on b.email = a.email without b.id < a.id and deleting every duplicated row, survivors included.
- Deleting duplicate customers first, so ON DELETE CASCADE wipes their orders.
- Cleaning duplicates without adding a unique constraint, so the next import creates them again.
Likely interviewer follow-ups
- Delete duplicate rows by email, keeping the oldest. Write it two ways.
- How would you find people who are probably the same but spelled differently?
- What must you do with child records before deleting duplicates?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Deduplicating Rows Using Self Joins with hands-on SQL practice and interview Q&A.