Deduplicating Tables Using ROW_NUMBER() OVER (PARTITION BY ...)
Keep one survivor row per key with ROW_NUMBER and filter rn = 1.
In plain words
Group the copies, number them from best to worst, keep number 1 and remove the others.
Think of it like…
Cleaning up a contacts list with the same person saved three times: group the entries by phone number, keep the most recently updated one, and delete the rest.
Where you’ve seen it
A users table has the same email registered several times after a sign-up bug. You keep the most recently active account per lower-cased email, delete the rest, then add a unique index on LOWER(email) so it can't happen again.
Words you’ll hear
- Duplicate key
- The column or columns that define "the same record", such as email.
- Survivor
- The one row per key you keep, chosen by the ORDER BY.
- rn > 1
- The duplicates to remove.
- Unique constraint
- Prevents new duplicates once the data is clean.
Visual diagram
Theory & example queries
Finding and ranking duplicates
Start by measuring the problem: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1 shows which keys are duplicated and how badly. Then decide what makes two rows "the same"; often that means normalising the key, for example LOWER(TRIM(email)).
ROW_NUMBER() OVER (PARTITION BY key ORDER BY updated_at DESC, id DESC) numbers each group. The ORDER BY is a business decision: newest, oldest, most complete, or a preferred source. Add a unique tiebreaker such as id so the survivor is deterministic.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
WITH ranked AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY LOWER(email) ORDER BY updated_at DESC, id DESC ) AS rn FROM users )SELECT *FROM rankedWHERE rn = 1;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output3 sample rows
| id | updated_at | rn | |
|---|---|---|---|
| 12 | asha@example.com | 2026-11-18 10:20:00 | 1 |
| 28 | ben@example.com | 2026-11-17 14:05:00 | 1 |
| 35 | chen@example.com | 2026-11-19 08:45:00 | 1 |
Note: Illustrative survivor rows; SELECT * would include every remaining users column.
Key takeaway: PARTITION BY defines "same"; ORDER BY defines "best".
Deleting safely and preventing it again
Delete by primary key: compute the ranks in a subquery and delete the ids where rn > 1. In MySQL you can't select from the table you're deleting from directly (error 1093), but wrapping the ranking in a derived table works. Tables without a primary key can use PostgreSQL's ctid as a row identifier.
Run it inside a transaction and compare the deleted count with your earlier duplicate count before committing. Then add a unique constraint or unique index on the normalised key; otherwise the same bug creates new duplicates next week.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
DELETE FROM usersWHERE id IN ( SELECT id FROM ( SELECT id, ROW_NUMBER() OVER ( PARTITION BY LOWER(email) ORDER BY updated_at DESC, id DESC ) AS rn FROM users ) t WHERE rn > 1 );PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Illustrative case with seven non-survivor duplicate rows; the real count depends on duplicate groups.
Key takeaway: Delete by primary key inside a transaction, then add a unique index.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Measure the duplicates
Count rows per key with HAVING COUNT(*) > 1 to see how many keys are affected and how many extra rows there are.
GROUP BY LOWER(email)HAVING COUNT(*) > 1When to use it & trade-offs
What it is
To remove duplicates while keeping one row per key, number the rows in each duplicate group with ROW_NUMBER() OVER (PARTITION BY key ORDER BY …). The row numbered 1 is the survivor; rows numbered 2 and above are the duplicates to filter out or delete. The ORDER BY decides which copy survives.
Why it matters: Duplicate rows from retried imports, double-submitted forms or messy joins are one of the most common data problems. DISTINCT can't help when the duplicates differ in some column (like updated_at). Interviewers ask this to see whether you can choose a survivor deliberately and delete safely.
When to reach for it
- Cleaning up duplicate users, customers or events
- Keeping the latest version of each record in a staging table
- Reading one row per key in reports
When to avoid or be careful
- ROW_NUMBER without a meaningful ORDER BY, which keeps a random copy
- Deleting without checking the expected count first
- Cleaning up without adding a constraint, so duplicates return
ROW_NUMBER vs DISTINCT vs DISTINCT ON
Strengths: Full control over which copy survives; works for SELECT and DELETE.
Watch out: A little more code.
Strengths: Simplest.
Watch out: Can't pick a survivor; useless when any column differs.
Strengths: Short: DISTINCT ON (email) … ORDER BY email, updated_at DESC.
Watch out: PostgreSQL-only, and not directly usable for DELETE.
Interview signals & numbers to know
When this topic comes up
- “Remove duplicate rows but keep one”
- “Keep the latest record per user”
- Retried or double-processed imports
- “Why doesn't DISTINCT remove these duplicates?”
- MySQL error 1093
Benchmarks & rules of thumb
- rn = 1
- the survivor
- rn > 1
- the rows to delete
- COUNT(*) - COUNT(DISTINCT key)
- number of extra rows
Common mistakes & follow-ups
Common interview mistakes
- Using DISTINCT on rows that differ in a timestamp column and wondering why duplicates remain.
- Leaving the survivor to chance with no tiebreaker in ORDER BY.
- Deduplicating on email without normalising case and spaces, so Asha@X.com and asha@x.com both survive.
Likely interviewer follow-ups
- How would you delete duplicates from a table that has no primary key?
- How do you decide which duplicate to keep?
- How would you stop duplicates from being created in the first place?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Deduplicating Tables Using ROW_NUMBER() OVER (PARTITION BY ...) with hands-on SQL practice and interview Q&A.