DEV Community

Sachin Ghatage
Sachin Ghatage

Posted on

Suppose you have duplicate rows in a table. How can you delete all duplicates but keep one copy using SQL only?

using CTE + ROW_NUMBER()

WITH CTE AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Name, DeptId ORDER BY EmpId) AS rn
FROM Employees
)
DELETE FROM CTE
WHERE rn > 1;

This will number the records according to name and deptId , starts with 1 contiues until next record with different name and deptid is found this way it will delete all the duplicate records keeping one copy

Top comments (0)