SQL: Finding duplicates in table


Looking for rows with some duplicate values in some column(s) is very common. I’m not saying that’s something hard.  I was asked about this. Here is my solution.

1
2
3
4
SELECT [Name], COUNT([Name]) AS NumOccurrences
FROM [People]
GROUP BY [Name]
HAVING ( COUNT( [Name] ) > 1 )

And the query to get all PKs ( primary keys ) for rows with duplicate [Name]:

1
2
3
4
5
6
7
SELECT [uid]
FROM [People]
WHERE [Name] IN (
SELECT [Name]
FROM [People]
GROUP BY [Name]
HAVING ( COUNT([Name]) > 1 ))

That’s all!