Select and Delete Duplicate Records

Theo: nguyenhaidang.name.vn | 13/06/2017 - 09:39

 Developers often face situations when they find their column have duplicate records and they want to delete it. A good developer will never delete any data without observing it and making sure that what is being deleted is the absolutely fine to delete. Before deleting duplicate data, one should select it and see if the data is really duplicate.

In this video we are demonstrating two scripts – 1) selects duplicate records 2) deletes duplicate records.

We are assuming that the table has a unique incremental id. Additionally, we are assuming that in the case of the duplicate records we would like to keep the latest record. If there is really a business need to keep unique records, one should consider to create a unique index on the column. Unique index will prevent users entering duplicate data into the table from the beginning. This should be the best solution. However, deleting duplicate data is also a very valid request. If user realizes that they need to keep only unique records in the column and if they are willing to create unique constraint, the very first requirement of creating a unique constraint is to delete the duplicate records.

Here is the script which is used in the video.

USE tempdb
GO
CREATE TABLE TestTable (ID INTNameCol VARCHAR(100))
GO
INSERT INTO TestTable (IDNameCol)
SELECT 1''First''
UNION ALL
SELECT 2''Second''
UNION ALL
SELECT 3''Second''
UNION ALL
SELECT 4''Second''
UNION ALL
SELECT 5''Second''
UNION ALL
SELECT 6''Third''
GO
-- Selecting Data
SELECT *
FROM TestTable
GO
-- Detecting Duplicate
SELECT NameColCOUNT(*) TotalCount
FROM TestTable
GROUP BY NameCol
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
GO
-- Deleting Duplicate
DELETE
FROM 
TestTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM TestTable
GROUP BY NameCol)
GO
-- Selecting Data
SELECT *
FROM TestTable
GO
DROP TABLE TestTable
GO

Link video: https://youtu.be/ioDJ0xVOHDY?t=4

Nguồn: https://blog.sqlauthority.com/2012/12/19/sql-server-select-and-delete-duplicate-records-sql-in-sixty-seconds-036-video/

Back Head Print
Tin khác

Search GridView with Paging on TextBox KeyPress using jQuery in ASP.Net    (28/07/2010)

Bootstrap AutoComplete TextBox example using jQuery TypeAhead plugin in ASP.Net with C# and VB.Net    (28/07/2010)

Disable Button and Submit button after one click using JavaScript and jQuery    (29/07/2010)

Split and convert Comma Separated (Delimited) String to Table in SQL Server    (01/09/2010)

Select Column values as Comma Separated (Delimited) string in SQL Server using COALESCE    (01/09/2010)