top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

SQL Server: How can we remove duplicate rows from a table

+4 votes
82 views
SQL Server: How can we remove duplicate rows from a table
posted Dec 6, 2013 by Neeraj Pandey

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

2 Answers

+1 vote

Suppose you have table1 which has duplicate values and looks like this:

new
pen
book
pen
like
book
book
pen

Now say we want table2 which should look like this:

new 
pen
book
like

It can be achieved as (where table2 can itself be a variable or temp table also)

INSERT INTO table2 (name)
SELECT name FROM table1 GROUP BY name
answer Dec 7, 2013 by Salil Agrawal
0 votes

Say your table definition is

MyTable
-----------
RowID int not null identity(1,1) primary key,
Column varchar(20) not null,

Assuming no nulls, you GROUP BY the unique columns, and SELECT the MIN (or MAX) RowId as the row to keep. Then, just delete everything that didn't have a row id:

DELETE MyTable 
FROM MyTable
LEFT OUTER JOIN (
   SELECT MIN(RowId) as RowId, Column
   FROM MyTable 
   GROUP BY Column
) as KeepRows ON
   MyTable.RowId = KeepRows.RowId
WHERE
   KeepRows.RowId IS NULL
answer Dec 7, 2013 by Kumar Mitrasen
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...