MS SQL Tips & Tricks

How to remove duplicates leaving only first occurrence

This problem is very similar to finding duplicates. We just need to make sure that the only record left will be the first one. That is modification of query from finding duplicates

delete Table 
from (
	select t.Id
	from  Table t
	where exists(
		  Select t2.Id from Table t2
		  where t.Column=t2.Column and
			   t2.Id<t2.Id
	   )
	) as x
where x.Id=Table.Id	

It simply finds records for each exists any similar record with smaller ID.

The same situation, if we want only last occurrence to be left.

delete Table 
from (
	select t.Id
	from  Table t
	where exists(
		  Select t2.Id from Table t2
		  where t.Column=t2.Column and
			   t2.Id>t2.Id
	   )
	) as x
where x.Id=Table.Id	

Learn more tricks

Add Comment

Comments

14th July 2021

30 mg accutane from canada online

zivacle

31st July 2021

safe place to buy cialis online

zivacle

8th September 2021

Cialis

AwasmaB

8th September 2021

http://buytadalafshop.com/ - Cialis

ceagods

12th September 2021

100 Mg Viagra Preise

ivermectin rosacea

12th September 2021

best place to buy stromectol

wabrhyday