Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate records except the first record in SQL

I want to remove all duplicate records except the first one.

Like :

NAME
R
R
rajesh
YOGESH
YOGESH

Now in the above I want to remove the second "R" and the second "YOGESH".

I have only one column whose name is "NAME".

like image 681
Yogesh Sharma Avatar asked Jul 12 '26 12:07

Yogesh Sharma


1 Answers

Use a CTE (I have several of these in production).

;WITH duplicateRemoval as (
    SELECT 
        [name]
        ,ROW_NUMBER() OVER(PARTITION BY [name] ORDER BY [name]) ranked
    from #myTable
    ORDER BY name
)
DELETE
FROM duplicateRemoval
WHERE ranked > 1;

Explanation: The CTE will grab all of your records and apply a row number for each unique entry. Each additional entry will get an incrementing number. Replace the DELETE with a SELECT * in order to see what it does.

like image 60
Eli Avatar answered Jul 15 '26 07:07

Eli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!