DELETE DUPLICATE ROWS FROM A TABLE:



At times you will face the issue of duplicate data in the table. As we have to create reports and get data in Relational form, we have to remove the duplicate records and make the records unique.  There are various ways to achieve this and I am listing few of them over here.

You have Table Emp_Details having columns:

Name varchar(20),
Age varchar(20),
Address varchar(20)

I. Using Temporary Table:

Select *  into #temp
from Emp_Details
group by Name, Age, Address
having count(*) =1

Now, Truncate the original table

Truncate table Emp_Details

Again, inserting the records from the temporary table to Emp_Details

insert Emp_Details (Name, Age, Address)
Select Name, Age, Address from #temp

This will insert only distinct records.

ii. Using CTE:

With cte as
( Select  Name, Age, Address, Row_Number() over (partition by name, age, address order by name) as Num
 from Emp_Details
)
Delete from cte
where num > 1

iii. Using Derived Table:

DELETE A
FROM
(
SELECT name,salary, ROW_NUMBER() OVER (PARTITION BY name,salary ORDER BY name) AS rn
FROM Tab
) A
WHERE A.rn > 1



Comments

Popular posts from this blog

Query Execution Plan - Basics