Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 59/ 160
03. Joins & Relational Querying

Deduplicating Rows Using Self Joins

Remove near-duplicates by pairing rows against a preferred survivor.

IntermediateSelf-Join Dedup · Survivor Row3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Delete exact duplicate eventsQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1DELETE FROM events a USING events b2WHERE3  b.user_id = a.user_id4  AND b.event_type = a.event_type5  AND b.occurred_at = a.occurred_at6  AND b.id < a.id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
DELETE 12

Note: Illustrative PostgreSQL status for 12 rows with an older matching event ID retained.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Map every duplicate to its survivorQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  a.id AS duplicate_id,3  MIN(b.id) AS survivor_id4FROM5  contacts a6  JOIN contacts b ON lower(trim(b.email)) = lower(trim(a.email))7  AND b.id < a.id8GROUP BY9  a.id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
duplicate_idsurvivor_id
184
294
4133

Note: Illustrative normalized-email duplicates; MIN(b.id) identifies the oldest surviving contact.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

MIN(b.id) is the oldest row in the group.

Key takeaway: Normalise or fuzzy-match, merge children to the survivor, then delete.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Rule

Define what a duplicate is

Pick the matching columns and how to normalise them: exact email, lower-cased email, or name plus postcode.

Focus at this step

lower(trim(email))

What to watch at this step
Survivor
lowest id
Tip: use ← → to move between steps

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

Self-join (b.id < a.id)
Best for: Reviewing pairs, fuzzy matches, small duplicate groups

Strengths: Shows exactly which row duplicates which; supports similarity conditions.

Watch out: Pairs grow quadratically in large groups.

ROW_NUMBER() OVER (PARTITION BY key)
Best for: Exact duplicates with a rich survivor rule

Strengths: One pass; survivor by any ORDER BY, like latest activity.

Watch out: Can't express fuzzy matching between rows.

GROUP BY key, MIN(id)
Best for: Simple "keep the lowest id" cleanups

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?
Interview tip: Write the SELECT of pairs first, mention merging children and the unique index, then the DELETE. The order shows you treat deletion as the last, careful step.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Deduplicating Rows Using Self Joins with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Querying Star Schemas (Joining Fact Tables to Multiple Dimension Tables)
Next topic
Visualizing & Debugging Complex Multi-Join Queries