r/learnSQL • • 22d ago

How many ways can you find duplicate rows in a table?

I was cleaning a customers table and needed to find duplicate emails. I found a few different ways to do it,and now I’m curious how many more exist.

  1. GROUP BY with HAVING
    2.ROW_NUMBER()
    3.Self JOIN
    The first one is the simplest. The second one is great when you want to delete the extras and keep just one row.

What other ways do you know? Bonus points for creative ones!

4 Upvotes

6 comments sorted by

1

u/slrworkbooks 22d ago

SELECT *

FROM (SELECT *, COUNT(*) OVER (PARTITION BY Email) AS Cnt FROM dbo.Customers) x

WHERE Cnt > 1

ORDER BY Email;

-- Or

SELECT c.*

FROM dbo.Customers c

WHERE EXISTS (SELECT 1 FROM dbo.Customers d

WHERE d.Email = c.Email AND d.CustomerID <> c.CustomerID);

1

u/analytical_mind_ 22d ago

You can also use COUNT() over (PARTITION BY email) or EXISTS to identify duplicates. If you’re working in Power BI or excel, Power Query’s Group by and remove duplicates options are handy too. The key is deciding what makes a record a duplicate before removing anything.

1

u/ihaxr 20d ago

Export to Excel

Conditional formatting > Highlight > Duplicate Values

1

u/Lucky_Cable_3145 20d ago edited 20d ago

Get a list of the IDs for each email with duplicates, something like

SELECT
c.emailaddr,
COUNT(c.emailaddr) as numEmail,
LISTAGG(c.CustomerID , ', ') WITHIN GROUP (ORDER BY c.CustomerID ASC) AS duplicateIDs
FROM dbo.Customers c
GROUP BY c.emailaddr
ORDER BY numEmail desc;

edit: removed the links reddit added