I have duplicate rows in my table, how can I delete them based on a single column's value?
Eg
uniqueid, col2, col3 ...
1, john, simpson
2, sally, roberts
1, johnny, simpson
delete any duplicate uniqueIds
to get
1, John, Simpson
2, Sally, Roberts
You probably have a row id that is assigned by the DB upon insertion and is actually unique. I'll call this rowId in my example.
You can remove duplicates by grouping on the thing that is supposed to be unique (whether it be one column or many), then you grab a rowId from each group, and delete everything else besides those rowIds. In the inner query, everything in the table will have a rowId except for the duplicate rows.
You could also use MAX instead of MIN with similar results.
Here is simple magic to remove duplicates
You can
DELETE
from a cte:The
ROW_NUMBER()
function assigns a number to each row.PARTITION BY
is used to start the numbering over for each item in that group, in this case each value ofuniqueid
will start numbering at 1 and go up from there.ORDER BY
determines which order the numbers go in. Since eachuniqueid
gets numbered starting at 1, any record with aROW_NUMBER()
greater than 1 has a duplicateuniqueid
To get an understanding of how the
ROW_NUMBER()
function works, just try it out:You can adjust the logic of the
ROW_NUMBER()
function to adjust which record you'll keep or remove.For instance, perhaps you'd like to do this in multiple steps, first deleting records with the same last name but different first names, you could add last name to the
PARTITION BY
:You have many ways for deleting the duplicate records some of them are below...........
Different ways to delete Duplicate records
Using Row_Number() function and CTE
DELETE FROM table WHERE uniqueid='1' AND col2='john'
Or you changecol2='john'
tocol2='johnny'
. Depends on which record you want to delete.How did you end up with two same "unique" IDs in the first place?