Query to delete duplicate Records in SQL Server 2005

Posted: July 3, 2008 in Important SQL Query, Interview Questions, SQL Server, Utlities
Tags: ,

Suppose we have the situation to delete some duplicate records in our table. Suppose consider one table

create table #Test
(
EmpID int,
EmpName varchar(50)
)

–Insert the Records into #Test table

insert into #Test values(1,’Daya‘)
insert into #Test values(1,’Daya‘)
insert into #Test values(1,’Daya‘)

Now i have two duplicate records inserted and i want to delete those records. The following query will delete the duplicate records

–Query to Delete Duplicate Records

WITH Emp AS (SELECT ROW_NUMBER ( ) OVER ( PARTITION BY EmpID, EmpName ORDER BY EmpID ) AS RNUM FROM #Test )
DELETE FROM Emp WHERE RNUM > 1

 

Advertisement
Comments
  1. Vinodh says:

    If the records,then this query will help us.
    if there two different records having duplicates.Then, how to remove the duplicates of these two records.

  2. dayananthan says:

    Please provide one example as what exactly you want

  3. chandra mohan says:

    thanks your answer is right
    but that is so complex
    good luck

  4. Rakis says:

    Good One
    Thanks!!!!!!!!

  5. the query working well but need to understand i appreciate if could you explain about given query to delete the duplicate records.

    Thank you

  6. Govind says:

    WITH Emp AS (SELECT ROW_NUMBER ( ) OVER ( PARTITION BY EmpID, EmpName ORDER BY EmpID ) AS RNUM FROM #Test )
    DELETE FROM Emp WHERE RNUM > 1

    can u explain it in detail.
    i couldn’t undrestand
    Thanks

  7. webtips says:

    good one…

    I find two other method to solve the issue.

    Delete Duplicate records in SQL Server

  8. ramesh says:

    very nice post.your solution solve my problem.

  9. deepika says:

    The solution is good one,it is helpful

  10. That was very helpful my friend. Thank you so much.

  11. Rajendiran.M says:

    Hi,

    It is working fine.But i couldn’t understand . any simple method.

  12. how we delete all rows of the table.

  13. Prabin says:

    Thanks, this was exactly what I wanted. As suggested by Rajendiran, it would be great if you can provide a small explanation, so that the non-SQL experts can understand.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s