Delete Duplicate Emails
Medium
SQLDELETESelf Join
Problem
Schema: Person(id INT, email VARCHAR) with id as PK.
Delete duplicate rows so each email is kept exactly once — the row with the smallest id per email survives.
Example 1
Input: (1,a) (2,b) (3,a)
Output: after: (1,a) (2,b)
Constraints
- Don't change
idof the surviving rows.
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
SQL
DELETE p1
FROM Person p1
JOIN Person p2 ON p2.email = p1.email AND p2.id < p1.id;
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Delete Duplicate Emails interactively → ← All solutions