Home >Database >Mysql Tutorial >How to Delete Duplicate Records in SQL Server Using TSQL?

How to Delete Duplicate Records in SQL Server Using TSQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-12 11:47:42154browse

How to Delete Duplicate Records in SQL Server Using TSQL?

Removing Duplicate Entries in SQL Server Tables

Problem:

Suppose you have an Employee table with a field called EmployeeName containing duplicate entries. How can you use T-SQL to remove these duplicate rows based on the EmployeeName column in SQL Server?

Solution:

Efficiently delete duplicate rows in SQL Server using T-SQL and window functions. By ordering the duplicates using an employee ID, we can retain only the first occurrence of each name.

<code class="language-sql">DELETE x
FROM (
  SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY EmployeeName ORDER BY empId)
  FROM Employee
) x
WHERE rn > 1;</code>

To review the rows slated for deletion before executing the DELETE statement, run this query:

<code class="language-sql">SELECT *
FROM (
  SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY EmployeeName ORDER BY empId)
  FROM Employee
) x
WHERE rn > 1;</code>

The above is the detailed content of How to Delete Duplicate Records in SQL Server Using TSQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn