Skip to main content

LeetCode 196. Delete Duplicate Emails SQL Solution

Problem

LeetCode SQL Problem

  1. Delete Duplicate Emails

Person table

IdEmail
1john@example.com
2bob@example.com
3john@example.com
4emily@example.com
5phil@example.com
6bob@example.com

Solution - Group By + Common Table Expression

Delete Duplicate Emails
-- Generate a KEEP list
-- When there are duplicate emails, we'll keep the record with the minimum Id value
WITH IDsToKeep
AS (
SELECT Min(Id) AS Id
FROM Person
GROUP BY Email
)
-- Delete records with Id not in the KEEP list
DELETE
FROM Person
WHERE Id NOT IN (
SELECT Id
FROM IDsToKeep
)

Query Output

IdEmail
1john@example.com
2bob@example.com
4emily@example.com
5phil@example.com

Solution - Self Join

Delete Duplicate Emails
-- Use Self Join to detect duplicate Person Ids that have duplicat emails.
-- When there are duplicate emails, we'll keep the record with the minimum Id value
DELETE P1
FROM Person AS P1
INNER JOIN Person AS P2 ON P1.Id > P2.Id
AND P1.Email = P2.Email

Query Output

IdEmail
1john@example.com
2bob@example.com
4emily@example.com
5phil@example.com