MySQL Delete Duplicate Rows
This code removes duplicate rows and keeps the first one (the lowest id). We use the same users table from the find duplicates code.
Tutorials Class - Output Window
| id | name | |
|---|---|---|
| 1 | Ravi | ravi@mail.com |
| 2 | Sita | sita@mail.com |
| 3 | Amit | ravi@mail.com |
| 4 | Neha | neha@mail.com |
| 5 | Sita K | sita@mail.com |
Step 1: check what will be deleted
SELECT u1.*
FROM users u1
JOIN users u2
ON u1.email = u2.email AND u1.id > u2.id;
This shows rows 3 and 5. These are the extra copies.
Step 2: delete them
DELETE u1
FROM users u1
JOIN users u2
ON u1.email = u2.email AND u1.id > u2.id;
Now the table has only one row for each email:
Tutorials Class - Output Window
| id | name | |
|---|---|---|
| 1 | Ravi | ravi@mail.com |
| 2 | Sita | sita@mail.com |
| 4 | Neha | neha@mail.com |
Note:
Always run the SELECT first and take a backup of the table. A DELETE cannot be undone after it is committed. To stop duplicates in future, add a UNIQUE constraint on the email column.
Related: MySQL DELETE, MySQL JOINS and Constraints.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |