Archive

Posts Tagged ‘how to remove duplicates in a table in sql server’

T-SQL : Delete duplicates in a table using Query

Following are the queries that will delete all available duplicates in a table, please refer the query below

Declare @Duplicates table (Name nvarchar(50), Age int, BookingID int)

insert into @Duplicates
select 'Dinesh',26,145 union all
select 'Latheesh',26,142 union all
select 'Sathish',26,144 union all
select 'Sathish',26,144 union all
select 'Sathish',26,144 union all
select 'Sathish',26,154 union all
select 'Dinesh',26,145 union all
select 'Dinesh',26,145  

delete del
from
(select
row_number() over(partition by Name, Age, BookingID order by Name)row_id,*
from @Duplicates) del
where del.row_id >1

select * from @Duplicates

Before deletion:

blog1

Output:

blog2

Alternatively, the same operation can be done using a CTE as shown below

Declare @Duplicates table (Name nvarchar(50), Age int, BookingID int)

insert into @Duplicates
select 'Dinesh',26,145 union all
select 'Latheesh',26,142 union all
select 'Sathish',26,144 union all
select 'Sathish',26,144 union all
select 'Sathish',26,144 union all
select 'Sathish',26,154 union all
select 'Dinesh',26,145 union all
select 'Dinesh',26,145  

;With del
as
(select
row_number() over(partition by Name, Age, BookingID order by Name)row_id,*
from @Duplicates) 

delete from del
where del.row_id >1

select * from @Duplicates
Advertisements
%d bloggers like this: