SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to delete duplicates in a table?

The following sample SQL Server T-SQL script demonstrates the deletion of duplicates on columnA using a derived table (b) w:

DELETE a

FROM   TableX a

       INNER JOIN (SELECT   columnA,

                            minID = min(TableXID)

                   FROM     TableX

                   GROUP BY columnA) b

         ON a.columnA = b.columnA

            AND a.TableXID > b.minID

 

Starting with SQL Server 2005, CTE can be used to delete duplicates.

-- T-SQL using ranking function ROW_NUMBER to delete duplicates

USE tempdb;

SELECT EmployeeId = CONVERT(INT,EmployeeID), ManagerID

INTO Employee

FROM AdventureWorks.HumanResources.Employee

GO

 

INSERT Employee VALUES (100, 109)

INSERT Employee VALUES (150, 109)

INSERT Employee VALUES (190, 109)

GO

;WITH CTE AS

  (SELECT rn=ROW_NUMBER() OVER( PARTITION BY EmployeeID ORDER BY ManagerID), *

   FROM Employee)

DELETE CTE

WHERE rn > 1

GO

-- (3 row(s) affected)

 

DROP TABLE Employee

 

------------

-- SQL eliminate duplicates with DISTINCT

------------

USE tempdb;

GO

-- Create test data

SELECT ProductID=CONVERT(int, ProductID), ProductName=Name,

       ListPrice, Color

INTO Product

FROM AdventureWorks2008.Production.Product

GO

-- (504 row(s) affected)

-- Create duplicates

INSERT Product SELECT * FROM Product

GO

-- (504 row(s) affected)

 

-- Eliminate duplicates with DISTINCT

SELECT DISTINCT * INTO newProduct FROM Product

-- (504 row(s) affected)

SELECT COUNT(*) FROM Product    -- 1008

SELECT COUNT(*) FROM newProduct -- 504

GO

DROP TABLE tempdb.dbo.Product

DROP TABLE tempdb.dbo.newProduct

GO

------------

 

 

Related KB article: How to remove duplicate rows from a table in SQL Server

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.