Monday, September 9, 2024

How can I delete duplicate rows from a table?

 To delete duplicate rows while keeping one instance of each, you can use a Common Table Expression (CTE):

WITH CTE AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Column1, Column2 ORDER BY (SELECT NULL)) AS rn FROM YourTableName ) DELETE FROM CTE WHERE rn > 1;

This CTE assigns a row number to each duplicate row and deletes all but the first instance.