Search code examples
sqlsql-serversql-deleteduplex

Add DELETE to query that returns duplicate records | SQL Server


i need your help.

I've this query that detect a duplex records:

SELECT
    name, email, COUNT(*)
FROM
    users
GROUP BY
    name, email
HAVING 
    COUNT(*) > 1

So i need to delete the results, so i've try this:

Delete FROM
    users
GROUP BY
    name, email
HAVING 
    COUNT(*) > 1

but doesn't work. Could tell me an help ? thank.


Solution

  • Try this query:

    DELETE
    FROM users
    WHERE ID NOT IN
    (SELECT MAX(ID)
    FROM users
    GROUP BY name, email)