Another way in SQL to Delete Duplicate Records

Another way in SQL to Delete Duplicate Records

Using a CTE to delete duplicates

Some of my other posts show how to find and delete duplicate records from SQL Server. This is another way to delete duplicate records using a CTE.

A Common Table Expression (CTE) is a named result set in a SQL query. CTEs help keep your code organized and allow you to perform multi-level aggregations on your data, like finding the average of a set of counts.

WITH cte
     AS (SELECT ROW_NUMBER() OVER (PARTITION BY Col1, Col2, Col3
                                       ORDER BY ( SELECT 0)) RN
         FROM   #MyTable)
DELETE FROM cte
WHERE  RN > 1;

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.