Thursday, July 3, 2008

How to find duplicate records in a database

Often a developer finds it necessary to deal with duplicate data in a database. They may have a need to provide a list of duplicate records or delete the duplicate records. The below methods provide an easy approach to working with duplicate data.

To create a list of the duplicate records with a count of the number of duplicates per record:

SELECT column, COUNT( column )
FROM table
GROUP BY column
HAVING count( column ) > 1

To create a list of ALL duplicate records, where there will be a listing for EACH record:

SELECT column
FROM TABLE
WHERE column in (SELECT column FROM table
HAVING count(column) > 1 )
ORDER BY column

No comments: