How can I find duplicate entries and delete the oldest ones in SQL?
Find duplicates and delete oldest one
Here is the Code
create table #Product (
ID int identity(1, 1) primary key,
Name varchar(800),
DateAdded datetime default getdate()
)
insert #Product(Name) select 'Chocolate'
insert #Product(Name,DateAdded) select 'Candy', GETDATE() + 1
insert #Product(Name,DateAdded) select 'Chocolate', GETDATE() + 5
select * from #Product
;with Ranked as (
select ID,
dense_rank()
over (partition by Name order by DateAdded desc) as DupeCount
from #Product P
)
delete R
from Ranked R
where R.DupeCount > 1
select * from #Product
delete from table a1 where exists (select * from table a2 where a2.name = a1.name and a2.date > a1.date)