Custom Search
Logiclabz
  • Home
  • Sql Server
  • Delete duplicate rows on table with/without primary key in Sql Server 2005

Delete duplicate rows on table with/without primary key in Sql Server 2005

The sql server query to delete duplicate records on table with/without primary key in Sql Server 2005

Table without primary key:

select * from #tablewithoutprimary
table without primary key

Sql Server 2005 query to identify duplicate records on table without primary key

With temptable as 
(
 select ROW_NUMBER() over (PARTITION BY course, subject ORDER BY course) AS rownumber,* 
FROM #tablewithoutprimary
)
select * FROM temptable
delete duplicate on table with primary key

Rows with rownumber greater than 1 are duplicate

hence duplicate rows can be deleted as

With temptable as 
(
 select ROW_NUMBER() over (PARTITION BY course, subject ORDER BY course) AS rownumber,* 
FROM #tablewithoutprimary
)
delete from temptable where rownumber > 1

Table with primary key:

select * from #tablewithprimary
table with primary key

Sql Server 2005 query to identify duplicate records on table with "id" primary key

select * from #tablewithprimary where id not in 
(select min(id) from #tablewithprimary group by course,subject) 
delete duplicate on table with primary key

hence duplicate rows can be deleted as

delete from #tablewithprimary where id not in 
(select min(id) from #tablewithprimary group by course,subject) 


Comments

  • Prem says:
    Jul 01, 10

    Hi All, I want to display all duplicate records in the table. My query has to fetch all the records which are duplicate(First Name or Last Name). Also I want the ability to also pull names where there might be a middle initial placed in the end of the first name field, (i.e., "Maria Z. " vs. "Maria") as well. Please guide me to find this. Table: ID FirstName LastName 1 Zach H Hoffman 2 Zach Hoffman 3 Troy Hoffman 4 Shawn Livermore 5 Prem S 6 Jony Hoffman H 7 Zach Modan I need the query to filter......... ID FirstName LastName 1 Zach H Hoffman 2 Zach Hoffman 3 Troy Hoffman 6 Jony Hoffman H 7 Zach Modan I hope this example will give you clear idea..... Thanks in Advance Prem

  • Prem says:
    Jul 01, 10

    Hi All, I want to display all duplicate records in the table. My query has to fetch all the records which are duplicate(First Name or Last Name). Also I want the ability to also pull names where there might be a middle initial placed in the end of the first name field, (i.e., "Maria Z. " vs. "Maria") as well. Please guide me to find this. Table: ID FirstName LastName 1 Zach H Hoffman 2 Zach Hoffman 3 Troy Hoffman 4 Shawn Livermore 5 Prem S 6 Jony Hoffman H 7 Zach Modan I need the query to filter......... ID FirstName LastName 1 Zach H Hoffman 2 Zach Hoffman 3 Troy Hoffman 6 Jony Hoffman H 7 Zach Modan I hope this example will give you clear idea..... Thanks in Advance Prem


Leave a reply


Do you like this post?