MySQL + SQL · Lesson 1

Delete Duplicate Rows

The Problem

Remove duplicate rows from a table while keeping one copy of each.

Using a Self Join

-- keep the row with the smallest id, delete the rest
DELETE e1 FROM employees e1
INNER JOIN employees e2
WHERE e1.id > e2.id
  AND e1.email = e2.email;

How it Works

We compare rows with the same email; for each duplicate pair we delete the one with the larger id, keeping the first.

Summary

  • Self-join the table on the duplicate column, delete rows with the larger id.
  • This keeps one copy of each unique value.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n