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

[sourcecode language=”sql” wraplines=”false”]
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
[/sourcecode]

Before deletion:

blog1

Output:

blog2

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

[sourcecode language=”sql” wraplines=”false”]
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
[/sourcecode]

This entry was posted in T-SQL and tagged , , , , . Bookmark the permalink.

8 Responses to T-SQL : Delete duplicates in a table using Query

  1. Abraham-Cruce says:

    Great website, keep it up!

  2. Betty says:

    Simple and great

  3. keo nha cai says:

    Perfects, works like a charm

  4. keo nha cai says:

    Thank you 🙂

  5. roulette says:

    It worked for me

  6. carig says:

    Great ThANKS

  7. Julian says:

    Nice, it works

  8. joker casino culiacan says:

    Good Post Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *