SQL

Delete Duplicate Records In SQL Using Common Table Expression

In many scenarios, a developer needs to delete duplicate records from the table frequently according to their requirements.

Below are a few SQL lines of code that detect and delete duplicate records from a table in the SQL database.

Following is an example of a table with duplicate records.

 

 

 

2 out of 5 records, 1 & 5 are duplicates.

Now let’s delete those duplicate records using SQL queries.

Let’s assume that the table name is [UserRole], so the query for deleting the duplicate records will be as below.

WITH tblTempUserRole as    
(    
SELECT ROW_NUMBER() Over(PARTITION BY [UserName], [RoleName] ORDER BY UserName)    
   As RowNumber, * FROM [UserRole]
)    
DELETE FROM tblTempUserRole WHERE RowNumber >1    
  
SELECT * FROM [UserRole]

after executing the query, the above query will delete all duplicate records. then run a select query to get the records and we will get only 4 records.

Below are the records after execution.

 

 

 

Tabish Rangrej

Tabish Rangrej is an Experienced .NET Team Leader, software engineer, and Author with a demonstrated history of working in the IT industry. He has quite well experience in developing, communicating, managing, and writing in his field. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, ASP.NET CORE, Angular, AngularJS, Web API, SQL, Entity Framework, JavaScript, Jquery, Different Integrations like Quickbooks, Stripe, Google APIs, Zoho, Orion, Xero, etc., Different versioning tools like TFS, SVN, GIT, etc. and Windows services. Strong engineering professional with a Master of Computer Applications - MCA focused on Computer Science from Veer Narmad South Gujarat University, Surat. Tabish is always ready to accept new challenges and learn new things, he would like to serve better for the community.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago