Delete Duplicate Emails Problem


Description

LeetCode Problem 196.

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

1
2
3
4
5
6
7
8
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:

1
2
3
4
5
6
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+


MySQL Solution

1
2
3
delete p1 
from Person p1, Person p2
where p1.Email = p2.Email and p1.Id > p2.Id




Related Posts

Department Top Three Salaries Problem

LeetCode 185. Write a SQL query to find employees who...

Department Highest Salary Problem

LeetCode 184. Write a SQL query to find employees who...

Rising Temperature Problem

LeetCode 197. Write an SQL query to find all dates’...

Delete Duplicate Emails Problem

LeetCode 196. Write a SQL query to delete all duplicate...

Duplicate Emails Problem

LeetCode 182. Write a SQL query to find all duplicate...

Customers Who Never Order Problem

LeetCode 183. Write a SQL query to find all customers...