11 February 2009

Removing Duplicates from a Table in SQL Server

Sometimes, in SQL, it is the routine operations that turn out to be the trickiest for a DBA or developer. The cleaning up, or de-duplication, of data is one of those. András runs through a whole range of methods and tricks, and ends with a a fascinating technique using CTE, ROW_NUMBER() and DELETE

Only rarely will you need to remove duplicate entries from a table on a production database. The tables in these databases should have a constraint, such as a primary key or unique constraint, to prevent these duplicate entries occurring in the first place. However, last year at SQL Bits 3 in Reading, I asked my audience how many of them needed to remove duplicate rows from a table, and almost eighty percent raised a hand.

How is it that duplicates can get into a properly-designed table?  Most commonly, this is due to changes in the business rules that define what constitutes a duplicate, especially after the merging of two different systems.  In this article, I will look at some ways of removing duplicates from tables in SQL Server 2000 and later versions, and at some of the problems that may arise.

Checking for Duplicates

On any version of SQL Server, you can identify duplicates using a simple query, with GROUP BY and HAVING, as follows:

The result indicates that there are two occurrences of the row containing the “duplicate row” text:

Removing Duplicate Rows in SQL Server

The following sections present a variety of techniques for removing duplicates from SQL Server database tables, depending on the nature of the table design.

Tables with no primary key

When you have duplicates in a table that has no primary key defined, and you are using an older version of SQL Server, such as SQL Server 2000, you do not have an easy way to identify a single row. Therefore, you cannot simply delete this row by specifying a WHERE clause in a DELETE statement.

You can, however, use the SET ROWCOUNT 1 command, which will restrict the subsequent DELETE statement to removing only one row. For example:

In the above example, only one row is deleted. Consequently, there will be one remaining row with the content “duplicate row”. If you have more than one duplicate of a particular row, you would simply adjust the ROWCOUNT accordingly. Note that after the delete, you should reset the ROWCOUNT to 0 so that subsequent queries are not affected.

To remove all duplicates in a single pass, the following code will work, but is likely to be horrendously slow if there are a large number of duplicates and table rows:

When cleaning up a table that has a large number of duplicate rows, a better approach is to select just a distinct list of the duplicates, delete all occurrences of those duplicate entries from the original and then insert the list into the original table.

As a variation of this technique, you could select all the data, without duplicates, into a new table, delete the old table, and then rename the new table to match the name of the original table:

In this solution, the SELECT DISTINCT will select all the rows from our table except for the duplicates. These rows are immediately inserted into a table named tempTable. This is a temporary table in the sense that we will use it to temporarily store the unique rows. However, it is not a true temporary table (i.e. one that lives in the temporary database), because we need the table to exist in the current database, so that it can later be renamed, using sp_Rename.

The sp_Rename command is an absolutely horrible way of renaming textual objects, such as stored procedures, because it does not update all the system tables consistently. However, it works well for non-textual schema objects, such as tables.

Note that this solution is usually used on table that has no primary key. If there is a key, and there  are foreign keys referencing the rows that  are identified as being  duplicates, then the foreign key constraints need to be dropped and re-created again during the table swap.

Tables with a primary key, but no foreign key constraints

If your table has a primary key, but no foreign key constraints, then the following solution offers a way to remove duplicates that is much quicker, as it entails less iteration:

Unfortunately, this sort of technique does not scale well.

If your table has a reliable primary key, for example one that has an assigned a value that can be used in a comparison, such as a numeric value in a column with the IDENTITY property enabled, then the following approach is probably the neatest and best. Essentially, it deletes all the duplicates except for the one with the highest value for the primary key. If a table has a unique column such as a number or integer, that will reliably return just one value with  MAX() or MIN(), then you can use this technique  to identify the chosen survivor of the group of duplicates.

This can be simplified even further, though the logic is rather harder to follow.

Tables that are referenced by a Foreign Key

If you’ve you’ve set up your constraints properly then you will be unable to delete duplicate rows from a table that is referenced by another table, using the above techniques unless you have specified cascading deletes in the foreign key constraints.

You can alter existing foreign key constraints by adding a cascading delete on the foreign key constraint. This means that rows in other tables that refer to the duplicate row via a foreign key constraint will be deleted.  Because you will lose the referenced data as well as the duplicate, you are more likely to wish to save the duplicate data in its entirety first in a holding table.  When you are dealing with real data, you are likely to need to identify the duplicate rows that are being referred to, and delete the duplicates that are not referenced, or merge duplicates and update the references. This task will probably have to be done manually in order to ensure data integrity.

Tables with columns that cannot have a UNIQUE constraint

Sometimes, of course, you may have columns on which you cannot define a unique constraint, or you cannot even use the DISTINCT keyword. Large object types, like NTEXT, TEXT and IMAGE in SQL Server 2000 are good examples of this.  These are data types that cannot be compared, and so the above solutions would not work.

In these situations, you will need to add an extra column to the table that you could use as a surrogate key. Such a surrogate key is not derived from the application data. Its value may be automatically generated, similarly to the identity columns in our previous examples. Unfortunately, in SQL Server, you cannot add an identity column to a table as part of the ALTER TABLE command. The only way to add such a column is to rebuild the table, using SELECT INTO and the IDENTITY() function, as follows:

The above will create the duplicateTable4_Copy table. This table will have an identity column named id, which will already have unique numeric values set. Note that although we are creating an Identity column, uniqueness is not enforced in this case; you will need to add a unique index or define the id column as a primary key.

Using a cursor

People with application development background would consider using a cursor to try to eliminate duplicates. The basic idea is to order the contents of the table, iterate through the ordered rows, and check if the current row is equal to the previous row. If it does, then delete the row. This solution could look like the following in T-SQL:

The above script will not work, because once you apply the ORDER BY clause in the cursor declaration the cursor will become read-only. If you remove the ORDER BY clause, then there will be no guarantee that the rows will be in order, and checking two subsequent rows would no longer be sufficient to identify duplicates. Interestingly, since the above example creates a small table where all the rows fit onto a single database page and duplicate rows are inserted in groups, removing the ORDER BY clause does make the cursor solution work. It will fail, however, with any table that is larger and has seen some modifications.

New Techniques for Removing Duplicate Rows in SQL Server 2005

SQL Server 2005 has introduced the row_number() function, which provides an alternative means of identifying duplicates. Rewriting the first example, for tables with no primary key, we can now assign a row number to each row in a duplicate group, with a command such as:

The result will show:

In the above example, we specify an ordering and partitioning for the row_number() function. Note that the row_number() is a ranking window function, therefore the ORDER BY and the PARTITION BY in the OVER clause are used only to determine the value for the nr column, and they do not affect the row order of the query. Also, while the above is similar to our previous GROUP BY clause, there is a big difference concerning the returned rows. With GROUP BY you must use an aggregate on the columns that are not listed after the GROUP BY. With the OVER clause there is no such restriction, and you can get access to the individual rows in the groups specified by the PARTITION BY clause. This gives us access to the individual duplicate rows, so we can get not only the number of occurrences, but also a sequence number for the individual duplicates. To filter out the duplicate rows only, we could just put the above query into a CTE or a subquery. The CTE approach is as follows:

This is not really any different from what we could do on SQL Server 2000.  However, here comes an absolutely amazing feature in SQL Server 2005 and later: We can refer to, and identify, a duplicate row based on the row_number() column and then, with the above CTE expression, we can use a DELETE statement instead of a SELECT, and directly remove the duplicate entries from our table.

We can demonstrate this technique with the following example:

This solution will even work with large objects, if you stick to the new large object types introduced in SQL Server 2005: i.e. use VARCHAR(MAX) instead of TEXT, NVARCHAR(MAX) instead of NTEXT, and VARBINARY(MAX) instead of IMAGE. These new types are comparable to the deprecated TEXT, NTEXT and IMAGE, and they have the advantage that you will be able to use them with both DISTINCT and row_number().

 I find this last solution, using CTE, ROW_NUMBER() and DELETE, fascinating. Partly because now we can identify rows in a table when there is no other alternative way of doing it, and partly because it is a solution to a problem that should not, in theory, exist at all since production tables will have a unique constraint or a primary key to prevent duplicates getting into the table in the first place.

Keep up to date with Simple-Talk

For more articles like this delivered fortnightly, sign up to the Simple-Talk newsletter

This post has been viewed 305349 times – thanks for reading.

  • Rate
    [Total: 348    Average: 4.2/5]
  • Share

András Belokosztolszki

View all articles by András Belokosztolszki

Related articles

Also in SQL

Relational Algebra and its implications for NoSQL databases

With the rise of NoSQL databases that are exploiting aspects of SQL for querying, and are embracing full transactionality, is there a danger of the data-document model's hierarchical nature causing a fundamental conflict with relational theory? We asked our relational expert, Hugh Bin-Haad to expound a difficult area for database theorists.… Read more

Also in SQL Server

SQL Server System Functions: The Basics

Every SQL Server Database programmer needs to be familiar with the System Functions. These range from the sublime (such as @@rowcount or @@identity) to the ridiculous (IsNumeric()) Robert Sheldon provides an overview of the most commonly used of them.… Read more

Also in T-SQL Programming

SQL Server Metadata Functions: The Basics

To be able to make full use of the system catalog to find out more about a database, you need to be familiar with the metadata functions. They save a great deal of time and typing when querying the metadata. Once you get the hang of these functions, the system catalog suddenly seems simple to use, as Robert Sheldon demonstrates in this article.… Read more

Also in T-SQL Programming

Formatting SQL Code - Part the First

With the formatting of code, we sometimes do things because they've always been done that way, rather than making code easier to understand. Occasionally these habits get in the way of readability. Joe Celko goes deep into his memorybanks to explain how these deep-seated traditions started. … Read more
  • Rodney

    Excellent, Andras.
    Yet another Simple-Talk quality article that I am forwarding to my DBA team!

  • Anonymous

    This is going to my scripts repository.

  • randyvol

    Nice techniques !
    I’ll have to give these a try.

    With the exception of FK references, the approach I have taken is to use the group by/having count(*)>1 query to insert the rows into a table (usually the name of the table I want to cleanse with ‘_DUPS’ added to the end of the table).
    I also add a row_id column to the table I’m creating with an identity of (1,1).
    Finally I use an Order by on the grouped by columns.

    The result is all the duplicated rows added to the _DUPS table and nicely ordered with a sequential row_id.

    Next I delete the duplicate rows from the original table.

    Then I insert a single row from each duplicated rows set from the _DUPS table using the min(row_id) as the means to pick one copy of each set of duplicated rows to insert back into the original table.

    Has served me well over the years.

  • randyvol

    one way dups can happen in production systems…
    By the by –

    I can provide you an example of a ‘real-world’ problem that has hounded us for over a year on our commercial ERP package.

    As will sometimes occur with commercial packages, this one was modified by the vendor.

    Somewhere in their code (either the original or the modified source, we’re still waiting a resolution on where) is a bug that allows duplicate customer records to get created.

    The way this happens is the code uses system generated surrogate keys to “guarantee” distinctness. But if one loses sight of what is supposed to be distinct (i.e., the natural key, a customer number) and one doesn’t test to be sure the natural key is not being dup’d, then the system will happily and serenely keep duplicating, a customer record an infinite number of times, each time with a distinct surrogate key – which is not anything useful by itself.

  • hugosheb

    nice explanation
    thank you, now I get the row_number usage much better!

  • SQLDeveloper

    Another Cursor Method using TOP
    I liked the methods you have demonstrated here in this article.
    I liked the latest one a lot.

    I can suggest one more method with cursors using TOP key that I’m using and I prefer to use against such a case. You can consider this method too, check it at http://www.kodyaz.com/articles/delete-duplicate-records-rows-in-a-table.aspx

  • András

    Re: Randyvol and SQLDeveloper
    Hi Randyvol and SQLDeveloper,
    thank you for sharing your approaches.
    – Andras

  • Anonymous

    It’s Great Andras.
    Really very useful.

    Thank you,

  • Cyrille L

    Removing Duplicate Rows in SQL Server
    Hey Andras,

    This is the most extensive coverage yet of dealing with duplicate data. You made a great effort to cover all possible scenarios and the article came at a time when I need to dedup some tables in my company’s production databases. Thanks for saving my day. Thank you simple-talk.

  • James in the Midwest

    Removing Duplicates
    Good job…saved it in my SQL script reference folder

  • Anil Mahadev

    Awesome and very informative 🙂
    Great Article! 🙂

  • Anonymous

    remove duplicate data
    Fantastic. Thank you. I learn new technique to remove dup data.

  • monsterjta

    Wish I read this last week
    Great post. Very complete. I was just doing this for a customer last week. Wish I would had this article handy then!

  • Jeff Moden

    Dupe data happens
    One place where duplicate data happens all the time is in telephony… most companies just can’t seem to generate unique data. Even when they can, there are those folks who hit redial several times in the same minute because they’re desparate to get through but keep getting a recording. As soon as they hear the recording, they hit redial to try again. Some places have laws or rules that prohibit a customer from being billed more than once each minute no matter how many times they hit redial.

    Of course, the whole idea is to delete all the duplicates in the staging table before you move the data to it’s final resting place. Even the move has a test for existance so you don’t end up putting dupe data into the final table.

  • Rahul Bhatt

    Great Article! 🙂

  • Mega

    Wonder ful
    Great article! 🙂

  • amitb

    Duplicate Rows
    Hey Excellent article.

    Regarding Deleting dups from table having pk as – identity(int,1,1)
    wont this query work?

    DELETE FROM #table
    WHERE id Not IN (SELECT MAX(id)
    FROM #table
    GROUP BY data

  • NullPointer

    Duplicate Rows
    @amitb – yes it will work in a case where you have a PK with identity 1,1 – in that case, you already have a clear identifier that you can use to identify each row uniquely.

    The problem arises when you don’t – for example when the supposed “unique” key is the customer account number and you discover that there are now somehow two ‘ACC01’ entries that are 100% identical across *all* fields – that’s when you need to use row_number() to assign what is essentially a virtual identity() column to the data so you can weed out the duplicates.

  • krishnasrikanth

    Simple mathematical trick
    Supose you have table which u forgot to add primary key on a column, and all rows are appearing twice. This trick might work. Especially with large data, around 100,000 records and u have 200,000 records in table.

    select columns into temptable from maintable order by pk_forgotten_column.

    add column, ID bigint identity(1,1) to the temptable

    Now every second row is a duplicate one. remove them

    delete from temptable where ID%2=0

    now the temptable is the clean one, rename it to the main one. Simple.

  • msalim

    NOT EXISTS method
    <code style=’font-size: 12px;’><span style=’color:blue’>DELETE</span><br/>

  • msalim


  • msalim

    FROM @table t
    (SELECT *
    FROM @table
    GROUP BY data
    HAVING data = t.data
    AND MAX(id) = t.id)

  • capetownnatural

    Very Helpful Article
    Thanks András, a very helpful article!

  • Nirav Parikh

    Remove Duplicates From Table!!!
    With duplicates
    (Select *, ROW_NUMBER() Over (PARTITION by [Col_Name,…n] Order by [Col_Name,…n]) as Duplicate From Table_Name)
    delete From duplicates
    Where Duplicate > 1 ;

  • Doron

    Remove duplicate records in a smart way
    Hi There,

    Great examples you have there and here is another article on that subject as well.




  • RoniVered

    Thank you
    Very good article.
    I especially liked the last example with the CTE, ROW_NUMBER() and DELETE query.

    Thanks for teaching me something.

  • Izaychik

    Special Case with Grouping
    I need to count unique transactions during the month
    by client. Here how I do it:

    Select a.[Client ID], a.[Transaction Code], a.[Transaction Date] from DB a
    where a.[Transaction Code] in (..)
    and not exists
    (Select * from DB b
    Where b.[Client Id] = a.[Client ID] and b.[Transaction Code] =a.[Transaction Code]
    — This line filter a maximum transaction date
    and b.[Transaction Date] > a.[Transaction Date]
    — Next two lines group maximum values by year months
    and Year(b.[Transaction Date] = Year(a.[Transaction Date])
    and Month([b.[Transaction Date] = Month(a.[Transaction Date])

    what do you think?

Join Simple Talk

Join over 200,000 Microsoft professionals, and get full, free access to technical articles, our twice-monthly Simple Talk newsletter, and free SQL tools.

Sign up