SQL | Remove Duplicates without Distinct

DISTINCT is useful in certain circumstances, but it has drawback that it can increase load on the query engine to perform the sort (since it needs to compare the result set to itself to remove duplicates)

Below are alternate solutions :

1. Remove Duplicates Using Row_Number.



WITH CTE (Col1, Col2, Col3, DuplicateCount)
AS
(
  SELECT Col1, Col2, Col3,
  ROW_NUMBER() OVER(PARTITION BY Col1, Col2,
       Col3 ORDER BY Col1) AS DuplicateCount
  FROM MyTable
) SELECT * from CTE Where DuplicateCount = 1

2.Remove Duplicates using self Join
YourTable

emp_name   emp_address  sex  matial_status  
uuuu       eee          m    s
iiii       iii          f    s
uuuu       eee          m    s
SELECT emp_name, emp_address, sex, marital_status
from YourTable a
WHERE NOT EXISTS (select 1 
         from YourTable b
         where b.emp_name = a.emp_name and
               b.emp_address = a.emp_address and
               b.sex = a.sex and
               b.create_date >= a.create_date)

3. Remove Duplicates using group By

SELECT FirstName, LastName, MobileNo, COUNT(*) as CNT
FROM  CUSTOMER
GROUP BY FirstName, LastName, MobileNo;
HAVING COUNT(*)  = 1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.