Delete Duplicate Rows In SQL

Let's first create a table with duplicate entries in it.
  1. Create table Employees  
  2. (  
  3.   ID int, FirstName nvarchar(50), LastName nvarchar(50), Gender nvarchar(50), Salary int  
  4. )  
  5.   
  6. GO  
  7. Insert into Employees values(1, 'Mark''Hastings''Male', 60000)  
  8. Insert into Employees values(1, 'Mark''Hastings''Male', 60000)  
  9. Insert into Employees values(1, 'Mark''Hastings''Male', 60000)  
  10. Insert into Employees values(2, 'Mary''Lambeth''Female', 30000)  
  11. Insert into Employees values(2, 'Mary''Lambeth''Female', 30000)  
  12. Insert into Employees values(3, 'Ben''Hoskins''Male', 70000)  
  13. Insert into Employees values(3, 'Ben''Hoskins''Male', 70000)  
  14. Insert into Employees values(3, 'Ben''Hoskins''Male', 70000)  

The Delete query should delete all duplicate rows except one. Here is the SQL query that does the job.

PARTITION BY divides the query result set into partitions.
  1. WITH EmployeesCTE AS  
  2. (  
  3.   SELECT * , ROW_NUMBER()   
  4. OVER  
  5. (  
  6.   PARTITION BY ID ORDER BY ID) AS RowNumber FROM Employees  
  7. )  
  8. DELETE FROM EmployeesCTE WHERE RowNumber > 1
Ebook Download
View all
SQL Jobs
Read by 0 people
Download Now!
Learn
View all