SQL: Delete rows with duplicate value in a given column

Given a table with two columns, Id and Name, if the same Name appears more than once, delete the duplications.

1 AA
2 AA
3 D
4 F
5 D
create table MyTable (Id int identity(1, 1) primary key , Name varchar(255));

insert into MyTable (Name) Values ('AA');
insert into MyTable (Name) Values ('AA');
insert into MyTable (Name) Values ('D');
insert into MyTable (Name) Values ('F');
insert into MyTable (Name) Values ('D');

select Name, MIN(Id) as id into distincts from MyTable group by Name

select Name, COUNT(*) as count into duplicates from MyTable group by Name Having COUNT(*) > 1

select * from MyTable

delete from MyTable
where (exists (select * from duplicates where duplicates.Name=MyTable.Name))
and (not exists (select * from distincts where distincts.id=MyTable.Id))

select * from MyTable

Comments