Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete duplicate rows in a table

I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?

like image 327
Malik Daud Ahmad Khokhar Avatar asked Sep 18 '08 11:09

Malik Daud Ahmad Khokhar


People also ask

Can we delete duplicate rows in SQL?

We can use the SQL RANK function to remove the duplicate rows as well. SQL RANK function gives unique row ID for each row irrespective of the duplicate row. In the following query, we use a RANK function with the PARTITION BY clause.

How do you delete one of the two duplicate rows in a table?

So to delete the duplicate record with SQL Server we can use the SET ROWCOUNT command to limit the number of rows affected by a query. By setting it to 1 we can just delete one of these rows in the table. Note: the select commands are just used to show the data prior and after the delete occurs.

How do I remove duplicate rows from student table?

The basic syntax to eliminate duplicate records from a table is: SELECT DISTINCT column1, column2,.... columnN. FROM table _name.


1 Answers

I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp. EDIT: now with code snippet!

INSERT INTO TABLE_2 
SELECT DISTINCT * FROM TABLE_1
GO
DELETE FROM TABLE_1
GO
INSERT INTO TABLE_1
SELECT * FROM TABLE_2
GO
like image 178
Manrico Corazzi Avatar answered Oct 08 '22 17:10

Manrico Corazzi