Duplicate cleanup should start by defining which columns make two rows duplicates and by previewing the rows before deleting anything. The examples below treat name, class, mark, and sex as the duplicate data while id is the unique row identifier.
| id | name | class | mark | sex |
|---|---|---|---|---|
| 1 | John Deo | Four | 75 | female |
| 2 | Max Ruin | Three | 85 | male |
| 3 | Arnold | Three | 55 | male |
| 4 | Krish Star | Four | 60 | female |
| 5 | John Mike | Four | 60 | female |
| 6 | Alex John | Four | 55 | male |
| 7 | My John Rob | Fifth | 78 | male |
| 8 | Asruid | Five | 85 | male |
| 9 | Tes Qry | Six | 78 | male |
| 10 | Big John | Four | 55 | female |
| 11 | Ronald | Six | 89 | female |
| 12 | Recky | Six | 94 | female |
| 13 | John Deo | Four | 75 | female |
| 14 | Max Ruin | Three | 85 | male |
| 15 | Arnold | Three | 55 | male |
SELECT name, class, mark, sex, COUNT(*) AS copies
FROM student_duplicate
GROUP BY name, class, mark, sex
HAVING COUNT(*) > 1;
DELETE t1
FROM student_duplicate AS t1
INNER JOIN student_duplicate AS t2
ON t1.name = t2.name
AND t1.class = t2.class
AND t1.mark = t2.mark
AND t1.sex = t2.sex
AND t1.id > t2.id;
Reverse the ID comparison if your requirement is to keep the highest ID instead.
DELETE t1
FROM student_duplicate AS t1
INNER JOIN student_duplicate AS t2
ON t1.name = t2.name
AND t1.class = t2.class
AND t1.mark = t2.mark
AND t1.sex = t2.sex
AND t1.id < t2.id;
SELECT first and keep a backup before a destructive duplicate-removal query.If the table itself allows duplicate IDs because no PRIMARY KEY exists, a structure-preserving rebuild can remove rows that are identical across all columns.
CREATE TABLE student_duplicate_clean LIKE student_duplicate2;
INSERT INTO student_duplicate_clean
SELECT DISTINCT *
FROM student_duplicate2;
After checking the cleaned table, swap it into place instead of dropping the original before validation.
RENAME TABLE
student_duplicate2 TO student_duplicate_backup,
student_duplicate_clean TO student_duplicate2;
This approach uses CREATE TABLE ... LIKE so indexes and table attributes are preserved more reliably than with a plain CREATE TABLE ... SELECT.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.