What's the best way to dedupe a table?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
The best way to deduplicate a table is usually a two-step process: define exactly what counts as a duplicate, then remove or merge rows deterministically while adding constraints that stop the duplicates from returning. The SQL syntax is not the hardest part. The hard part is choosing the right business key and deciding which row should survive.
Define the Duplicate Rule First
Rows are duplicates only relative to some business meaning. Sometimes that means every column matches. More often it means one key or a small key set, such as email, external_id, or customer_id plus order_date.
Start with a grouping query.
This tells you which keys are duplicated. It does not tell you which row to keep, so you still need a tie-breaker such as earliest creation time, latest update time, or lowest primary key.
Use ROW_NUMBER to Identify the Extra Rows
Window functions are the clearest general-purpose tool for this job.
This shows the rows that would be removed if you keep the oldest row per email address. Review this output before you run any delete.
Delete Only After You Review the Survivor Logic
Once the ranking rule is correct, use it in a delete statement.
Run this inside a transaction if your database supports it.
During development or dry runs, use ROLLBACK instead of COMMIT until you are satisfied with the survivor logic.
Merge Before Delete When Rows Differ
Sometimes duplicate rows are not truly identical. One row may contain the correct phone number while another contains the freshest timestamp. In those cases, deleting extras blindly loses information.
The safer workflow is:
- choose the survivor row
- copy any missing or preferred values into it
- repoint foreign keys if necessary
- delete the extra rows
That is slower than a one-line delete, but it is the right approach when the duplicates contain partial truth rather than exact copies.
Prevent the Duplicates From Returning
Cleanup is incomplete unless you block recurrence. Add a unique constraint or unique index on the real business key.
If the key should be unique only for certain rows or needs special NULL handling, use the database-specific partial or filtered index features where available.
Also inspect the source of the duplicates. Common causes include race conditions, bad imports, missing validation, or retried jobs with no idempotency key.
Large Tables Need Operational Care
On very large tables, dedupe in chunks or use a staged rewrite if long locks would be dangerous.
A staged table lets you validate counts, indexes, and downstream behavior before swapping it into place. That can be safer than in-place deletes on high-volume systems.
Common Pitfalls
- Deduplicating on the wrong business key and deleting valid rows.
- Forgetting a deterministic survivor rule such as timestamp or primary key order.
- Deleting parent rows without considering child foreign keys.
- Cleaning up once and then failing to add a constraint or ingestion fix.
- Running destructive dedupe statements without a transaction, backup, or dry run.
Summary
- Define duplicates using a real business rule before writing deletion SQL.
- Use
ROW_NUMBER()to mark which rows should survive and which should go. - Merge data before deleting when duplicate rows contain different useful values.
- Add a unique constraint or index so the duplicates do not come back.
- For large tables, prefer transactions, dry runs, and staged cleanup over rushed deletes.
Related reading
- What's the best way to iterate an Android Cursor?
- What's the difference between BatchGetItem and Query in DynamoDB?
- What's the difference between comma separated joins and join on syntax in MySQL?
- What's the difference between deleteAllInBatch and deleteAll?
- What's the difference between greedy and heuristic algorithm?
- What's the difference between Minimmum Spanning Tree and Travelling Salesman Problems
- What's the difference between deletemany and remove in mongodb?
- What's the difference between findAndModify and update in MongoDB?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.