Description

Table: Person

Column NameType
idint
emailvarchar
  • id is the primary key column for this table.
  • Each row of this table contains an email. The emails will not contain uppercase letters.

Problem Statement

Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest id. Note that you are supposed to write a DELETE statement and not a SELECT one.

Return the result table in any order.

The query result format is in the following example.

Example 1:

Input:

  • Person table:
idemail
1john@example.com
2bob@example.com
3john@example.com

Output:

idemail
1john@example.com
2bob@example.com

Explanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1.

Solution

The problem is asking us to delete a duplicate email but ensure that you need to delete not the first instance of the same email. This can be solved using SELF JOIN with itself. This way you can verify that the record you’re deleting occurs more than once and you do not end up deleting the first instance.

You join these two tables based on the email column, but delete only rows from p1 where p1.id is greater than p2.id.

1DELETE p1 FROM Person p1, Person p2
2    WHERE p1.email = p2.email AND p1.id > p2.id;