Saturday, May 19, 2012

Removing Duplicates through SQL Query

February 14, 2010 by · 1 Comment 

Suppose we have a table in SQL Server, that has duplicates in it.

CREATE TABLE T1
(
ProductName varchar(50)
)

INSERT INTO T1
VALUES
(‘Computer’),
(‘Computer’),
(‘Printer’),
(‘Printer’),
(‘Printer’),
(‘Scanner’),
(‘Scanner’),
(‘Scanner’),
(‘Scanner’),
(‘Camera’),
(‘Flash Drive’),
(‘Flash Drive’)

now use the following query, that will remove duplicates in the temporary table that we just created:

DELETE D FROM
(SELECT ProductName,ROW_NUMBER() OVER (ORDER BY ProductName ASC) AS ROWID  FROM T1 ) D,
(SELECT ProductName,ROW_NUMBER() OVER (ORDER BY ProductName ASC) AS ROWID  FROM T1 ) E
where D.ProductName = E.ProductName AND D.ROWID < E.ROWID

Top Blogs

Comments

One Response to “Removing Duplicates through SQL Query”
  1. neyronius says:

    What about MySql?

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

*