How to retrieve duplicate rows in a table?
How to delete the duplicate entries in a table?

Answer Posted / skybeaver

/* selecting duplicate rows in a table */
select col1, col2, ..., colN, count(*)
from TableName
group by col1, col2, ..., colN
having count(*) > 1

/* deleting duplicate rows from a table */
select col1, col2, ..., colN, count(*) as "Duplicates"
into #duplicates
from TableName
group by col1, col2, ..., colN
having count(*) > 1

delete TableName
from TableName t, #duplicates d
where t.col1 = d.col1 and
....
t.colN = d.colN

/* damn I'm good! */

Is This Answer Correct ?    11 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Can two tables share a primary key?

523


How to find the source of a table in sql server?

530


What is a View ? Can we insert, Update and delete a view?

632


what is package and it uses and how can u call a package

1563


What is encryption key?

84






Explain the functionalities that views support?

697


explain different types of constraints? : Sql server database administration

518


How to create hyperlink from returned sql query ?

627


What is the server name in sql server?

560


Can a cursor be updated? If yes, how you can protect which columns are updated?

524


How to get nth highest salary from employee table.

623


why does a sql statement work correctly outside of a user-defined function, but incorrectly inside it? : Sql server administration

560


How will you find out if there are expensive SQL statements running or not?

585


What are the acid properties?

555


What happens if ntwdblib.dll is missing on your machine?

639