Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to delete duplicate rows from same table?

Tags:

sql

suppose there is a employee table containing columns name, id and salary having 2 or more than two rows with same values in all three rows...then how to write a query to delete duplicate rows..

like image 847
Trupti Avatar asked Aug 31 '26 15:08

Trupti


2 Answers

Here is a nice way if you use Sql Server

with duplicates as
(select * ,ROW_NUMBER() over(

      partition by id,name, salary
      order by id,name, salary) rownum
from Person)
delete from duplicates where rownum > 1
like image 50
Jahan Zinedine Avatar answered Sep 03 '26 06:09

Jahan Zinedine


assuming ID is the primary key:

delete P
from Person P right outer join
(
   select name, min(id) as id
   from Person
   group by name
) unique_people
on P.id = unique_people.id
where P.id is NULL
like image 36
davek Avatar answered Sep 03 '26 06:09

davek