1

The following code returns a list of duplicate rows of a specific column. In this case I am trying to find duplicates of university name. And my problem is how could I delete the duplicates and leave just one copy for each different university_name?

    Select * from `university` where `university_name` in ( select `university_name` from `university` group by `university_name` having count(*) > 1 )

This is the result:

enter image description here Can you please explain I am very new to SQL! Thank you in advance!!

3
  • if you don't care which of the two you want to delete, group the entire result and select their IDs. Then delete the result. You could select the MAX(id) if you want to delete the second one. Commented Feb 12, 2016 at 7:56
  • If there are duplicates for a university_name, which row do you want to keep? Commented Feb 12, 2016 at 8:09
  • actually I might want to greater id to be deleted and keep the lowest id for future reference Commented Feb 12, 2016 at 8:17

3 Answers 3

5

1) If you want to keep the row with the lowest id value:

DELETE a
FROM university a, university b
WHERE a.id > b.id
AND  b.university_name=a.university_name

2) If you want to keep the row with the highest id value:

DELETE a
FROM university a, university b
WHERE a.id < b.id
AND  b.university_name=a.university_name
Sign up to request clarification or add additional context in comments.

1 Comment

I was not able to check if this works but thank you for the help
1

Try this:

DELETE  u
FROM    university u
        LEFT JOIN
        (
            SELECT MIN(ID) ID, university_name
            FROM    university
            GROUP   BY university_name
        ) v ON  u.ID = v.ID AND
                u.university_name = v.university_name
WHERE   v.ID IS NULL

Comments

0

Delete the duplicates and keep the row with oldest id

DELETE a
FROM university a
JOIN university b ON a.university_name = b.university_name
WHERE a.id > b.id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.