Wednesday, July 13, 2011

SQL: Deleting duplicate records from table

Here is one way to delete duplicate records from a table:

Consider we have some duplicate records in TempTable which has a unique identifier column called "RowId".

delete from TempTable
where RowId not in
(
select min(ROWID)
from TempTable
group by column1, column2,...
)

For each duplicate set of duplicate records, the above query retains one row with minimum RowId and deletes all other duplicate records. If you want to retain row with maximum RowId and delete all other duplicate records, then just replace the min() method with max().