Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Delete duplicates with single Delete?

Author  Topic 

calvinfoo
Posting Yak Master

129 Posts

Posted - 2011-05-12 : 02:18:27
I've figured out how to delete duplicates records as follow.

Questions:
1. is it possible to delete duplicates with nothing but just a single Delete query?



CREATE TABLE #TEST(ID TINYINT NULL, COL1 CHAR(1))
INSERT INTO #TEST(ID,COL1) VALUES (1,'A')
INSERT INTO #TEST(ID,COL1) VALUES (2,'B')
INSERT INTO #TEST(ID,COL1) VALUES (1,'A')
INSERT INTO #TEST(ID,COL1) VALUES (1,'B')
INSERT INTO #TEST(ID,COL1) VALUES (3,'C')
INSERT INTO #TEST(ID,COL1) VALUES (3,'C')
INSERT INTO #TEST(ID,COL1) VALUES (3,'C')

-- Step #1: Find and copy the duplicates to a temp table
SELECT * INTO #TempTable FROM #TEST GROUP BY ID, COL1
HAVING COUNT(*) > 1

-- Step #2: Delete the duplicates in the #TEST table
DELETE #TEST FROM #TEST, #TempTable
WHERE #TEST.ID = #TempTable.ID AND #TEST.COL1 = #TempTable.COL1

-- Step #3: Copy the duplicates and put it back into the original Table
INSERT #TEST SELECT * FROM #TempTable

-- Step #4: Drop the temp table
DROP TABLE #TempTable

lionofdezert
Aged Yak Warrior

885 Posts

Posted - 2011-05-12 : 02:42:45
;WITH cte
AS (SELECT ID,COL1,ROW_NUMBER()OVER (PARTITION BY ID,COL1 ORDER BY ID) AS RowNUm FROM #Test)

DELETE FROM cte
WHERE RowNum >1

--------------------------
http://connectsql.blogspot.com/
Go to Top of Page

calvinfoo
Posting Yak Master

129 Posts

Posted - 2011-05-12 : 03:26:43
Thanks for the solution. I didn't know it is that simple!
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-05-12 : 03:40:44
Also note that it will work from the versions starting from 2005

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -