Click here to Skip to main content
15,879,326 members
Articles / Database Development / SQL Server
Tip/Trick

How to remove duplicate rows in SQL Server 2005 when no key is present

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
20 Dec 2012CPOL 34.1K   16   6
This tip describes how to delete duplicate rows from a table that doesn't have a key.
An easy way to remove duplicate rows from a table in SQL Server 2005 is to use undocumented feature called %%lockres%%. This pseudo column shows the physical location of a row.
 
Note that this feature is undocumented and unsupported so use at your own risk!
 
A simple test-case. Create a test table:
SQL
CREATE TABLE TestTable (
   Column1 varchar(1),
   Column2 int
)
Add some rows with few duplicates:
SQL
INSERT INTO TestTable VALUES ('A', 1);
INSERT INTO TestTable VALUES ('A', 1); -- duplicate
INSERT INTO TestTable VALUES ('A', 2);
INSERT INTO TestTable VALUES ('B', 1);
INSERT INTO TestTable VALUES ('B', 2);
INSERT INTO TestTable VALUES ('B', 2); -- duplicate
INSERT INTO TestTable VALUES ('C', 2)
You can select the data to see that all seven rows are present:
SQL
SELECT *
FROM   TestTable a
ORDER BY a.Column1, a.Column2
Now let's delete the two duplicates using the %%lockres%%:
SQL
DELETE
FROM  TestTable
WHERE TestTable.%%lockres%%
      NOT IN (SELECT MIN(b.%%lockres%%)
              FROM   TestTable b
              GROUP BY b.column1, b.Column2)
And if you run the query again, you'll see that only five rows remain and duplicates have been deleted.
SQL
SELECT *
FROM   TestTable a
ORDER BY a.Column1, a.Column2
 
For more information about %%physloc%%, corresponding SQL Server 2008 pseudo column, see: Physical location of a row in SQL Server[^].
 
For SQL Server 2008 equivalent, see: How to remove duplicate rows in SQL Server 2008 when no key is present[^].

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Europe Europe
Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pin
archana naik6-Sep-13 20:27
professionalarchana naik6-Sep-13 20:27 
GeneralRe: My vote of 5 Pin
Wendelius16-Sep-13 2:53
mentorWendelius16-Sep-13 2:53 
GeneralReason for my vote of 5 Hats off to u Pin
ims.sanjay28-Feb-11 18:56
ims.sanjay28-Feb-11 18:56 
GeneralRe: Thanks Pin
Wendelius3-Aug-11 8:43
mentorWendelius3-Aug-11 8:43 
GeneralReason for my vote of 5 Excellent solution! Btw, Alternate i... Pin
DrABELL22-Feb-11 16:16
DrABELL22-Feb-11 16:16 
GeneralRe: Thank you. Yes, the alternate is very good. Pin
Wendelius3-Aug-11 8:43
mentorWendelius3-Aug-11 8:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.