To remove duplicate rows in sql select statement
- delete duplicate rows in sql using cte
- delete duplicate rows in sql server using cte
- how to delete duplicate rows in sql without using cte
- delete duplicate rows using cte
Delete duplicate rows in sql using rank.
Delete duplicate records in sql server using row_number
Problem
You want to delete duplicate rows from an existing table in SQL Server.
Example
A company has its employee data stored in the table with the columns and .
empName | dept |
---|---|
Jack Russel | Sales |
Jan Kowalski | HR |
John Doe | Sales |
Jack Russel | Sales |
John Doe | Sales |
Marta Wilson | HR |
Jack Russel | Sales |
Let’s say you want to delete duplicates from this table and leave only one record among the duplicates.
For example, Jack Russel from the Sales department has multiple records that are the same.
Solution
One way to approach this problem in SQL Server is to use a CTE and the function. Let’s look at the query:
WITH duplicates (name, dept, duplicate_count) AS ( SELECT name, dept, ROW_NUMBER() OVER(PARTITION BY name, dept ORDER BY name) FROM employees ) DELETE from duplicates WHERE duplicate_count > 1Here are the contents of the table after you run this query.
empName | dept |
---|---|
Jack Russel | Sales |
Jan Kowalski | HR |
John Doe | Sales |
Marta Wilson | HR |
Discussion
First, we create a CTE called with a new column called , which stores all r
- sql cte delete duplicates
- sql delete duplicates using cte