måndag 5 mars 2012

Deleting duplicate records in SQL

Perhaps not the most efficient way of deleting duplicate records in a table, but it's straightforward, keeps you online and does not require temporary tables and stuff:

delete from table
where id not in
(select max(dup.id) from table as dup group by dup.col1, dup.col2)


In short, the sub-select finds the set of unique IDs by grouping all columns and by utilizing the MAX aggregation (MIN should work as well). Then, a delete is performed on all the rows where ID is not in the set. Tada.

Inga kommentarer:

Skicka en kommentar