Open In App
Related Articles

SQL | Remove Duplicates without Distinct

Improve Article
Improve
Save Article
Save
Like Article
Like

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
The idea is to group according to all columns to be selected in output. For example, if we wish to print unique values of “FirstName, LastName and MobileNo”, we can simply group by all three of these.

SELECT FirstName, LastName, MobileNo
FROM  CUSTOMER
GROUP BY FirstName, LastName, MobileNo;
Unlock the Power of Placement Preparation!
Feeling lost in OS, DBMS, CN, SQL, and DSA chaos? Our Complete Interview Preparation Course is the ultimate guide to conquer placements. Trusted by over 100,000+ geeks, this course is your roadmap to interview triumph.
Ready to dive in? Explore our Free Demo Content and join our Complete Interview Preparation course.

Last Updated : 06 Apr, 2020
Like Article
Save Article
Similar Reads