2010. 6. 3. 23:56

T-SQL::Removing Duplication Data

 쉬운것 같으면서도 가끔 PK 생성때 중복 데이터가 있어서 안될 경우.

그게 또 대용량 데이터라면.. 참..  다시 데이터를 넣거나. 아니면 임시에 넣었다가 지우거나 그랬는데..

rowcount 쓰는 법이랑 2005의 row_number()를 이용할 수 있음.

 

Removing Duplicates from a Table in SQL Server
11 February 2009
 

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:

DECLARE @table TABLE (data VARCHAR(20))

INSERT INTO @table VALUES ('not duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('duplicate row')

 

SELECT  data

      , COUNT(data) nr

FROM    @table

GROUP BY data

HAVING  COUNT(data) > 1

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

data                 nr

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

duplicate row        2

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:

DECLARE @table TABLE (data VARCHAR(20))

INSERT INTO @table VALUES ('not duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('duplicate row')

 

SET ROWCOUNT 1

DELETE FROM @table WHERE data = 'duplicate row'

SET ROWCOUNT 0

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:

DECLARE @table TABLE (data VARCHAR(20))

INSERT INTO @table VALUES ('not duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('duplicate row')

 

SET NOCOUNT ON

SET ROWCOUNT 1

WHILE 1 = 1

   BEGIN

      DELETE   FROM @table

      WHERE    data IN (SELECT  data

                               FROM    @table

                               GROUP BY data

                               HAVING  COUNT(*) > 1)

      IF @@Rowcount = 0

         BREAK ;

   END

SET ROWCOUNT 0

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.

DECLARE @table TABLE(data VARCHAR(20))

INSERT INTO @table VALUES ('not duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('second duplicate row')

INSERT INTO @table VALUES ('second duplicate row')

 

SELECT   data

INTO     #duplicates

FROM     @table

GROUP BY data

HAVING   COUNT(*) > 1

 

-- delete all rows that are duplicated

DELETE   FROM @table

FROM     @table o INNER JOIN #duplicates d

         ON d.data = o.data

 

-- insert one row for every duplicate set

INSERT   INTO @table(data)

         SELECT   data

         FROM     #duplicates

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:

CREATE TABLE duplicateTable3(data VARCHAR(20))

INSERT INTO duplicateTable3 VALUES ('not duplicate row')

INSERT INTO duplicateTable3 VALUES ('duplicate row')

INSERT INTO duplicateTable3 VALUES ('duplicate row')

INSERT INTO duplicateTable3 VALUES ('second duplicate row')

INSERT INTO duplicateTable3 VALUES ('second duplicate row')

 

SELECT DISTINCT data

INTO    tempTable

FROM    duplicateTable3

GO

TRUNCATE TABLE duplicateTable3

DROP TABLE duplicateTable3

exec sp_rename 'tempTable', 'duplicateTable3'

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:

DECLARE @table TABLE(

      id INT IDENTITY(1, 1)

    , data VARCHAR(20)

    )

INSERT INTO @table VALUES ('not duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('duplicate row')

 

WHILE 1 = 1

   BEGIN

      DELETE   FROM @table

      WHERE    id IN (SELECT   MAX(id)

                        FROM     @table

                        GROUP BY data

                        HAVING   COUNT(*) > 1)

      IF @@Rowcount = 0

         BREAK ;

   END

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.

DECLARE @table TABLE (

      id INT IDENTITY(1, 1)

    , data VARCHAR(20)

    )

INSERT INTO @table VALUES ('not duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('duplicate row')

INSERT INTO @table VALUES ('second duplicate row')

INSERT INTO @table VALUES ('second duplicate row')

 

 

DELETE  FROM @table

FROM    @table o

        INNER JOIN ( SELECT data

                     FROM   @table

                     GROUP BY data

                     HAVING COUNT(*) > 1

                   ) f ON o.data = f.data

        LEFT OUTER JOIN ( SELECT    [id] = MAX(id)

                          FROM      @table

                          GROUP BY  data

                          HAVING    COUNT(*) > 1

                        ) g ON o.id = g.id

WHERE   g.id IS NULL

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

DELETE   FROM f

FROM     @table AS f INNER JOIN @table AS g

         ON g.data = f.data

              AND f.id < g.id

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:

CREATE TABLE duplicateTable4 (data NTEXT)

INSERT INTO duplicateTable4 VALUES ('not duplicate row')

INSERT INTO duplicateTable4 VALUES ('duplicate row')

INSERT INTO duplicateTable4 VALUES ('duplicate row')

INSERT INTO duplicateTable4 VALUES ('second duplicate row')

INSERT INTO duplicateTable4 VALUES ('second duplicate row')

 

 

SELECT  IDENTITY( INT, 1,1 ) AS id,

        data

INTO    duplicateTable4_Copy

FROM    duplicateTable4

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:

CREATE TABLE duplicateTable5 (data varchar(30))

INSERT INTO duplicateTable5 VALUES ('not duplicate row')

INSERT INTO duplicateTable5 VALUES ('duplicate row')

INSERT INTO duplicateTable5 VALUES ('duplicate row')

INSERT INTO duplicateTable5 VALUES ('second duplicate row')

INSERT INTO duplicateTable5 VALUES ('second duplicate row')

DECLARE @data VARCHAR(30),

    @previousData VARCHAR(30)

DECLARE cursor1 CURSOR SCROLL_LOCKS

    FOR SELECT  data

        FROM    duplicateTable5

        ORDER BY data

    FOR UPDATE

OPEN cursor1

 

FETCH NEXT FROM cursor1 INTO @data

WHILE @@FETCH_STATUS = 0

    BEGIN

          IF @previousData = @data

              DELETE  FROM duplicateTable5

              WHERE CURRENT OF cursor1

                 

          SET @previousData = @data

          FETCH NEXT FROM cursor1 INTO @data

    END

CLOSE cursor1

DEALLOCATE cursor1

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:

DECLARE  @duplicateTable4 TABLE (data VARCHAR(20))

INSERT INTO @duplicateTable4 VALUES ('not duplicate row')

INSERT INTO @duplicateTable4 VALUES ('duplicate row')

INSERT INTO @duplicateTable4 VALUES ('duplicate row')

INSERT INTO @duplicateTable4 VALUES ('second duplicate row')

INSERT INTO @duplicateTable4 VALUES ('second duplicate row')

 

SELECT  data

      , row_number() OVER ( PARTITION BY data ORDER BY data ) AS nr

FROM    @duplicateTable4

The result will show:

data                 nr

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

duplicate row        1

duplicate row        2

not duplicate row    1

second duplicate row 1

second duplicate row 2

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:

DECLARE  @duplicateTable4 TABLE (data VARCHAR(20))

INSERT INTO @duplicateTable4 VALUES ('not duplicate row')

INSERT INTO @duplicateTable4 VALUES ('duplicate row')

INSERT INTO @duplicateTable4 VALUES ('duplicate row')

INSERT INTO @duplicateTable4 VALUES ('second duplicate row')

INSERT INTO @duplicateTable4 VALUES ('second duplicate row')

;

WITH    numbered

          AS ( SELECT   data

                      , row_number() OVER ( PARTITION BY data ORDER BY data ) AS nr

               FROM     @duplicateTable4

             )

    SELECT  data

    FROM    numbered

    WHERE   nr > 1

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:

DECLARE  @duplicateTable4 TABLE (data VARCHAR(20))

INSERT INTO @duplicateTable4 VALUES ('not duplicate row')

INSERT INTO @duplicateTable4 VALUES ('duplicate row')

INSERT INTO @duplicateTable4 VALUES ('duplicate row')

INSERT INTO @duplicateTable4 VALUES ('second duplicate row')

INSERT INTO @duplicateTable4 VALUES ('second duplicate row')

;

WITH    numbered

          AS ( SELECT   data

                      , row_number() OVER ( PARTITION BY data ORDER BY data ) AS nr

               FROM     @duplicateTable4

             )

    DELETE  FROM numbered

    WHERE   nr > 1

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.



This article has been viewed 9208 times. 

이 글은 스프링노트에서 작성되었습니다.

'T-SQL' 카테고리의 다른 글

T_SQL::미 사용 Table  (0) 2010.06.15
데이터베이스 사이즈  (0) 2010.06.04
T-SQL::DB_Restore_move_to  (0) 2010.06.03
T-SQL::Convert hex value to String 32bit  (0) 2010.06.03