Find duplicate email addresses in a Users table.

Find duplicate emails in SQL with GROUP BY and HAVING, list the duplicate rows, ignore case and spaces, delete duplicates safely, and prevent them with a unique index.

0 0
Read Time:1 Minute, 24 Second
Users
id  name    email
1   Asha    asha@example.com
2   Ravi    ravi@example.com
3   Asha K  asha@example.com
4   Meera   Ravi@Example.com

The basic answer: GROUP BY with HAVING

SELECT email, COUNT(*) AS times
FROM Users
GROUP BY email
HAVING COUNT(*) > 1;

WHERE filters rows before grouping; HAVING filters groups after, which is why the count condition goes in HAVING.

Ignore case and spaces

Is “Ravi@Example.com” a duplicate of “ravi@example.com”? For email, usually yes.

SELECT LOWER(TRIM(email)) AS email, COUNT(*) AS times
FROM Users
GROUP BY LOWER(TRIM(email))
HAVING COUNT(*) > 1;

Show the full duplicate rows

SELECT *
FROM (
    SELECT u.*, COUNT(*) OVER (PARTITION BY LOWER(email)) AS cnt
    FROM Users u
) t
WHERE cnt > 1
ORDER BY LOWER(email), id;

Delete duplicates, keeping the oldest row

DELETE FROM Users
WHERE id IN (
    SELECT id FROM (
        SELECT id, ROW_NUMBER() OVER (PARTITION BY LOWER(email) ORDER BY id) AS rn
        FROM Users
    ) t
    WHERE rn > 1
);

The extra subquery level is needed in MySQL, which does not let you select from the table you are deleting from directly. Run it as a SELECT first and in a transaction, and check foreign keys that point to the rows you delete.

Prevent it

CREATE UNIQUE INDEX ux_users_email ON Users (LOWER(email));   -- PostgreSQL
-- or store emails lower-cased and add UNIQUE (email)

Follow-ups

  • WHERE versus HAVING.
  • Find customers who placed more than three orders last month.
  • What is the difference between UNIQUE and PRIMARY KEY?

This answer was written by Debugger’s Space as practice material. See how Cognizant hires, step by step, and more Cognizant practice questions.

Previous post What is cloud computing, and what are its benefits for a client?
Next post What does this recursive function return for n = 5?
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Close
0
Would love your thoughts, please comment.x
()
x