Skip to main content

LeetCode 182. Duplicate Emails SQL Solution

Problem

LeetCode SQL Problem

  1. Duplicate Emails

Person table

IdEmail
1a@b.com
2joe@test.com
3a@b.com
4joe@test.com
5a@b.com
6bob@test.com

Solution - Group By + Having

Find Duplicate Emails
-- Group by 'Email' and return 'Email' shared by more than 1 person Id
SELECT P.Email
FROM Person AS P
GROUP BY P.Email
HAVING count(P.Id) > 1

Query Output

Email
a@b.com
joe@test.com

Solution - Self Join Person Table

Find Duplicate Emails
-- Self Join 'Person' table to return combinations that have different person Id, but the same Email
SELECT DISTINCT P1.Email
FROM Person AS P1
INNER JOIN Person AS P2 ON P1.Id <> P2.Id
AND P1.Email = P2.Email

Query Output

Email
a@b.com
joe@test.com