Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove duplicate rows from a table in SQL Server [duplicate]

I have a table called table1 which has duplicate values. It looks like this:

new
pen
book
pen
like
book
book
pen

but I want to remove the duplicated rows from that table and insert them into another table called table2.

table2 should look like this:

new 
pen
book
like

How can I do this in SQL Server?

like image 371
meo Avatar asked Feb 27 '13 18:02

meo


1 Answers

Let's assume the field was named name:

INSERT INTO table2 (name)
SELECT name FROM table1 GROUP BY name

that query would get you all the unique names.

You could even put them into a table variable if you wanted:

DECLARE @Table2 TABLE (name VARCHAR(50))

INSERT INTO @Table2 (name)
SELECT name FROM table1 GROUP BY name

or you could use a temp table:

CREATE TABLE #Table2 (name VARCHAR(50))

INSERT INTO @Table2 (name)
SELECT name FROM table1 GROUP BY name
like image 112
Mike Perrenoud Avatar answered Oct 10 '22 18:10

Mike Perrenoud