Tuesday, January 20, 2009

Find and Clear Duplicates from sql table

To Find duplicates:

select [col1],[col2] from [TableName] where [condition]
group by [col1],[col2],[col3],[col4] having count(*) > 1


Example:

select CompanyName, State from registerinfo where RegisterinfoId >12000
group by Companyname, State, Add1, City having count(*) > 1


To Clear Duplicates:

SELECT *
FROM registerinfo
WHERE registerinfoid IN
(
SELECT registerinfoid
FROM registerinfo
WHERE EXISTS
(
SELECT NULL
FROM registerinfo AS tmptable
WHERE registerinfo.Companyname = tmptable.companyname and
registerinfo.add1 = tmptable.add1 and
registerinfo.State = tmptable.state
HAVING
registerinfo.registerinfoid > MIN(tmptable.registerinfoid)
)
)

1 comment: