Home > Database > Mysql Tutorial > How to Delete Duplicate Records in SQL Server Using a Single T-SQL Query?

How to Delete Duplicate Records in SQL Server Using a Single T-SQL Query?

Susan Sarandon
Release: 2025-01-12 11:51:45
Original
973 people have browsed it

How to Delete Duplicate Records in SQL Server Using a Single T-SQL Query?

Efficiently Removing Duplicate Rows in SQL Server

Imagine an Employee table containing an EmployeeName column. The goal is to remove duplicate rows based solely on the EmployeeName field. This can be achieved using a concise T-SQL query in SQL Server.

The Solution:

Leveraging window functions provides an elegant solution. The following query assigns a unique row number (rn) to each record within each EmployeeName group, ordered by empId. Subsequently, rows where rn is greater than 1 (i.e., duplicates) are deleted.

<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>
Copy after login

To preview the rows slated for deletion before executing the DELETE statement, run this SELECT 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>
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template