3

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..

3
  • 2
    Is this a homework question? It would help us if you specified which database you are using - as the syntax could differ. Commented Dec 22, 2010 at 15:20
  • 1
    Curious, what is the primary key of this table? Since typically most will use "ID" as the primary key. If "ID" is the primary key. Then how do you have duplicates? Sounds like a issue with your Primary Key constraint. Commented Dec 22, 2010 at 15:22
  • Sounds more like how to find duplicate questions on SO search: +delete +duplicate Commented Dec 22, 2010 at 15:31

5 Answers 5

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1 the comment is for me to increase the chance to find the link again, when I need it.
3

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

Comments

0

u can set unique key to to your field ... otherwise you can delete all the duplicate row by

delete from table_name where id=@id and name=@name

Comments

0

Insert the distinct rows from the original table to new temporary table. Delete data from original duplicate table then insert the distinct rows from the temporary table to original table.

select distinct * into temp From Emp;
delete from Emp;
insert into Emp(name,ID,salary) as select * from temp; 
drop table temp;

Comments

-1
DELETE TOP(1) FROM tablename WHERE columemane='name'

Supposing I have 2 duplicate rows in table student:

name | number | last name

Manoj | 1125256 | Sharma

Manoj | 1125256 | Sharma

I want to delete one using the following query

DELETE TOP(1) FROM student WHERE name='Manoj'

1 Comment

This works only when you have two rows, not if you have more duplicate records.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.