Reading history

How to Find and Delete Duplicate Rows in SQL

6 min read 0 views

Find duplicate rows in SQL with GROUP BY HAVING and ROW_NUMBER, delete all but one copy safely, and stop duplicates returning with a unique index.

Duplicate rows creep into almost every database: a form submitted twice, an import run twice, a contact typed in by two different staff members. They inflate counts, send customers two copies of every message, and break reports. This lesson shows how to find duplicates with GROUP BY and window functions, delete them safely while keeping one copy, and prevent them from coming back.

In this lesson you will learn

  • Finding duplicate values with GROUP BY … HAVING COUNT(*) > 1
  • Numbering copies with ROW_NUMBER()
  • Previewing and deleting all but one copy
  • Preventing duplicates with a unique index
  • The difference between deleting duplicates and SELECT DISTINCT

This lesson uses GROUP BY and HAVING and window functions.

Finding Duplicates

CREATE TABLE contacts (id INTEGER PRIMARY KEY, name TEXT, phone TEXT, city TEXT);
INSERT INTO contacts VALUES
 (1, 'Karim', '01711-000001', 'Dhaka'),
 (2, 'Rina',  '01811-000002', 'Khulna'),
 (3, 'Karim', '01711-000001', 'Dhaka'),
 (4, 'Joya',  '01911-000003', 'Sylhet'),
 (5, 'Rina',  '01811-000002', 'Khulna'),
 (6, 'Karim', '01711-000001', 'Dhaka'),
 (7, 'Tuhin', '01611-000004', 'Dhaka');

-- Which name + phone combinations appear more than once?
SELECT name, phone, COUNT(*) AS copies
FROM contacts
GROUP BY name, phone
HAVING COUNT(*) > 1
ORDER BY copies DESC;

-- Show every duplicate row with its position in its group
SELECT id, name, phone,
       ROW_NUMBER() OVER (PARTITION BY name, phone ORDER BY id) AS copy_no
FROM contacts
ORDER BY name, id;

Output

+-------+--------------+--------+
| name  | phone        | copies |
+-------+--------------+--------+
| Karim | 01711-000001 | 3      |
| Rina  | 01811-000002 | 2      |
+-------+--------------+--------+
(2 rows)

+----+-------+--------------+---------+
| id | name  | phone        | copy_no |
+----+-------+--------------+---------+
| 4  | Joya  | 01911-000003 | 1       |
| 1  | Karim | 01711-000001 | 1       |
| 3  | Karim | 01711-000001 | 2       |
| 6  | Karim | 01711-000001 | 3       |
| 2  | Rina  | 01811-000002 | 1       |
| 5  | Rina  | 01811-000002 | 2       |
| 7  | Tuhin | 01611-000004 | 1       |
+----+-------+--------------+---------+
(7 rows)
  • First decide what “duplicate” means. Here, two rows are the same contact if they have the same name and phone; the id is always different, so it is not part of the test.
  • GROUP BY name, phone puts identical contacts in one group, and HAVING COUNT(*) > 1 keeps only groups with more than one row. Karim appears 3 times and Rina twice.
  • ROW_NUMBER() OVER (PARTITION BY name, phone ORDER BY id) numbers the rows within each group. Copy 1 is the original (lowest id); every row with copy_no above 1 is an extra copy.

Deleting Duplicates and Preventing Them

CREATE TABLE contacts (id INTEGER PRIMARY KEY, name TEXT, phone TEXT, city TEXT);
INSERT INTO contacts VALUES
 (1, 'Karim', '01711-000001', 'Dhaka'), (2, 'Rina', '01811-000002', 'Khulna'),
 (3, 'Karim', '01711-000001', 'Dhaka'), (4, 'Joya', '01911-000003', 'Sylhet'),
 (5, 'Rina', '01811-000002', 'Khulna'), (6, 'Karim', '01711-000001', 'Dhaka'),
 (7, 'Tuhin', '01611-000004', 'Dhaka');

-- Preview: rows that would be deleted (all but the lowest id in each group)
SELECT id, name FROM contacts
WHERE id NOT IN (SELECT MIN(id) FROM contacts GROUP BY name, phone)
ORDER BY id;

-- Delete them, keeping the first copy of each contact
DELETE FROM contacts
WHERE id NOT IN (SELECT MIN(id) FROM contacts GROUP BY name, phone);

SELECT * FROM contacts ORDER BY id;

-- Stop new duplicates from being added
CREATE UNIQUE INDEX ux_contacts_name_phone ON contacts (name, phone);
-- fails: Karim with this phone already exists
INSERT INTO contacts (name, phone, city) VALUES ('Karim', '01711-000001', 'Dhaka');

-- SELECT DISTINCT hides duplicates in a result without deleting anything
SELECT DISTINCT city FROM contacts ORDER BY city;

Output

+----+-------+
| id | name  |
+----+-------+
| 3  | Karim |
| 5  | Rina  |
| 6  | Karim |
+----+-------+
(3 rows)

+----+-------+--------------+--------+
| id | name  | phone        | city   |
+----+-------+--------------+--------+
| 1  | Karim | 01711-000001 | Dhaka  |
| 2  | Rina  | 01811-000002 | Khulna |
| 4  | Joya  | 01911-000003 | Sylhet |
| 7  | Tuhin | 01611-000004 | Dhaka  |
+----+-------+--------------+--------+
(4 rows)

Error: UNIQUE constraint failed: contacts.name, contacts.phone

+--------+
| city   |
+--------+
| Dhaka  |
| Khulna |
| Sylhet |
+--------+
(3 rows)
  • The subquery SELECT MIN(id) … GROUP BY name, phone returns the id to keep from each group: 1, 2, 4 and 7.
  • Always run the query as a SELECT first. It shows exactly which rows (3, 5 and 6) the DELETE will remove.
  • The DELETE uses the same condition, leaving one row per contact.
  • A UNIQUE index on (name, phone) stops the problem returning: the next attempt to add a duplicate Karim is rejected. To merge instead of reject, use an UPSERT.
  • SELECT DISTINCT only hides repeated values in a query result. It does not change the table.

Deleting with ROW_NUMBER

When you need to keep a particular copy, such as the most recent, number the rows in a subquery and delete by row number. This works in PostgreSQL, SQLite and MySQL 8:

DELETE FROM contacts
WHERE id IN (
    SELECT id FROM (
        SELECT id, ROW_NUMBER() OVER (PARTITION BY name, phone ORDER BY id DESC) AS rn
        FROM contacts
    ) AS numbered
    WHERE rn > 1
);

ORDER BY id DESC makes the newest row number 1, so it is kept. In SQL Server you can delete straight from the CTE: WITH d AS (…) DELETE FROM d WHERE rn > 1;.

Common Mistakes

  1. Deleting without previewing. Run the SELECT version and back up the table first.
  2. Grouping by every column, including the id, which makes every row unique and finds nothing.
  3. Missing near-duplicates such as 'karim ' and 'Karim'. Compare LOWER(TRIM(name)) when case and spaces should not matter.
  4. Using NOT IN with a subquery that can return NULL. Here MIN(id) never returns NULL, but with other columns use NOT EXISTS.

Practice Exercises

Exercise 1. Find phone numbers that are shared by contacts with different names.

Show answer
SELECT phone, COUNT(DISTINCT name) AS names
FROM contacts
GROUP BY phone
HAVING COUNT(DISTINCT name) > 1;

On the sample data it returns no rows, because each phone number belongs to only one name.

Exercise 2. Count how many rows would remain after removing duplicates, without deleting anything.

Show answer
SELECT COUNT(*) AS unique_contacts
FROM (SELECT DISTINCT name, phone FROM contacts) AS u;

For the original seven rows this returns 4.

Frequently Asked Questions

What if the table has no id column?

Copy the distinct rows into a new table, check it, then swap the tables: CREATE TABLE contacts_clean AS SELECT DISTINCT * FROM contacts;. SQLite also has a hidden rowid, and PostgreSQL a ctid, that can tell identical rows apart.

Should I remove duplicates in SQL or in my application?

Clean existing data with SQL, then let the database prevent new duplicates with a unique constraint. Application checks alone can miss duplicates when two requests run at the same time.

Summary

  • Define which columns make two rows “the same”.
  • Find duplicates with GROUP BY … HAVING COUNT(*) > 1 or ROW_NUMBER().
  • Preview, then delete every row except the one you keep in each group.
  • Add a unique index so duplicates cannot return.

Next: SQL Triggers.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *