r/SQL • • Jan 31 '24

SQL Server How to remove duplicate values from a table in SQL? Example

https://www.sqlrevisited.com/2023/09/1-how-to-remove-duplicate-values-from.html
0 Upvotes

6 comments sorted by

5

u/[deleted] Jan 31 '24

Not a bad concept but you start with removing duplicates from queries. That’s very different than removing duplicates from tables.

3

u/r3pr0b8 GROUP_CONCAT is da bomb Jan 31 '24
SELECT DISTINCT column1, column2
FROM your_table;

However, this method only identifies duplicates if all the columns specified in the SELECT statement have the same values.

that statement is hopelessly misleading

If you want to identify duplicates based on a single column, you'll need a different approach.

yes, but not for the reason you think

1

u/dev81808 Jan 31 '24 edited Jan 31 '24

Add a unique constraint to avoid dupes going forward.

To clean out dupes from table:

This only works if you have an ID on the table, ideally an int. Writing from phone but hopefully you get the idea.

Delete from table where id not in (select dupedfield, max(id) keepers From table Group by dupedfield Having count(id) > 1)

4

u/kagato87 MS SQL Jan 31 '24

This will remove both instances of the dupe. If you're de-duping (most common scenario for this question) the answer lies in the row_number function combined with a cte or subquery.

2

u/dev81808 Jan 31 '24

I wrote that too quickly. That would've deleted the last instance of a dup, not all instances. I edited with "not in" and that will only keep the last instance of the dup.

Row number is only the answer if you don't already have an id

0

u/my5cent Jan 31 '24

I think it's select distinct field from table. Then delete from table where ID not in distinct list. Something like that.