Home > T-SQL > T-SQL : Delete duplicates in a table using Query

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: