How to remove duplicate rows from a SQL Server table by using a script

Article translations Article translations
Article ID: 70956 - View products that this article applies to.
This article was previously published under Q70956
Expand all | Collapse all

SUMMARY

You can use the following script to remove duplicate rows from a Microsoft SQL Server table:
   SELECT DISTINCT *
      INTO duplicate_table
      FROM original_table
      GROUP BY key_value
      HAVING COUNT(key_value) > 1

   DELETE original_table
      WHERE key_value
      IN (SELECT key_value
             FROM duplicate_table)

   INSERT original_table
      SELECT *
         FROM duplicate_table

     DROP TABLE duplicate_table
				
When this script is executed, it follows these steps:
  1. It moves one instance of any duplicate row in the original table to a duplicate table.
  2. It deletes all rows from the original table that also reside in the duplicate table.
  3. It moves the rows in the duplicate table back into the original table.
  4. It drops the duplicate table.

MORE INFORMATION

This method is simple. However, it requires that you have sufficient space available in the database to temporarily build the duplicate table.

Properties

Article ID: 70956 - Last Review: November 2, 2007 - Revision: 4.3
APPLIES TO
  • Microsoft SQL Server 2005 Standard Edition
  • Microsoft SQL Server 2005 Express Edition
  • Microsoft SQL Server 2005 Workgroup Edition
  • Microsoft SQL Server 2005 Developer Edition
  • Microsoft SQL Server 2005 Enterprise Edition
  • Microsoft SQL Server 2000 Personal Edition
  • Microsoft SQL Server 2000 Standard Edition
  • Microsoft SQL Server 2000, Workgroup Edition
  • Microsoft SQL Server 2000 Developer Edition
  • Microsoft SQL Server 2000 Enterprise Edition
  • Microsoft SQL Server 7.0 Standard Edition
  • Microsoft SQL Server 7.0 Service Pack 1
  • Microsoft SQL Server 6.5 Standard Edition
  • Microsoft SQL Server 6.0 Standard Edition
  • Microsoft SQL Server 4.21a Standard Edition
Keywords: 
kbprogramming KB70956

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com