Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Deleting Duplicate Rows

By Deepak Arjun,

To delete duplicate rows in Sql server is one of the tedious tasks. Duplicate rows might exist in a table because of bad database design or because constraints are not applied. Unlike Oracle where we get unique row-id for each row and using that we can delete duplicate records, there is no simple way to delete duplicate records in Sql Server.

One method used to delete duplicate records is to write a stored procedure, use cursor in that and delete row one by one. There is another simple interactive way to delete duplicate rows in Sql Server without using stored procedures and cursor.

I will use Enterprise manager for explanation but scripts can be used if duplicate records are to be deleted on regular basis from some table. Create one table OrderDetail with columns ShipmentId, OrderId, ArticleId and Quantity where ShipmentId, OrderId and ArticleId fields should be unique.

Add few duplicate records into this table.

Create a blank copy of table using:

Select * into OrderDetailCopy from OrderDetail where 1 = 0

Create Unique index on columns ShipmentId, OrderId and ArticleId. Also check Ignore duplicate key checkbox. Save the table.

Copy the records from OrderDetail into OrderDetailCopy using:

insert into OrderDetailCopy Select * from OrderDetail
You will get warning message:

Server: Msg 3604, Level 16, State 1, Line 1
Duplicate key was ignored.

Now you have OrderDetailCopy table without any duplicate rows.

Drop table OrderDetail using
Drop table OrderDetail

Rename table OrderDetailCopy to OrderDetail using

Sp_rename 'OrderDetailCopy','OrderDetail'

 

Total article views: 15068 | Views in the last 30 days: 8
 
Related Articles
SCRIPT

Deleting Duplicate Records

In Datawarehousing, a normal scenario is eleminating duplicate records/rows or deleting duplicate re...

FORUM

Deleting Duplicate Record in Production

Deleting Duplicate Record in Production

SCRIPT

Deleting Duplicate Records

This article explains a simple solution for the common problem in MSSQL 7.0/2000, finding & deleting...

FORUM

Delete duplicate records in a table

Delete duplicate records in a table

FORUM

delete duplicates

delete duplicates

Tags
t-sql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones