TechBuzzPro

MySQL Find Duplicates: Query & Delete Them

· 6 min read · Apps & Browsers

In this article
  1. Why Duplicates Happen
  2. Basic Query to Find Duplicates
  3. Finding All Rows That Are Duplicates
  4. Finding Duplicates on Multiple Columns
  5. How to Delete Duplicates (Safely)
  6. Using a Unique Index to Prevent Future Duplicates
  7. Common Mistakes and Pitfalls
  8. Frequently Asked Questions

To find duplicate values in a MySQL table, you use the GROUP BY and HAVING clauses to group rows by the column(s) that should be unique and then filter for groups with a count greater than one. For example, SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1; lists every duplicate email and how many times it appears. This article explains the exact syntax, how to see the full duplicate rows, and safe ways to remove them.

Why Duplicates Happen

Duplicate rows usually appear because a table lacks a unique constraint or primary key on the columns that should be unique. Common causes include:

  • Multiple data imports that were not checked for existing records.
  • Application code that inserts a row without first checking whether it already exists.
  • Merging data from several sources where the same entity appears under slightly different spellings or formats.
  • User-submitted forms that get submitted twice due to double-clicks or network retries.

Once duplicates exist, they can skew reports, cause double-counting in aggregates, and make queries slower because indexes are less effective. Finding them is the first step to cleaning the data.

Basic Query to Find Duplicates

The core pattern uses GROUP BY on the column(s) that should be unique, then HAVING COUNT(*) > 1 to keep only groups with more than one row.

SELECT column1, column2, COUNT(*)
FROM your_table
GROUP BY column1, column2
HAVING COUNT(*) > 1;

This returns one row per duplicate combination, along with the number of times it appears. For example, to find duplicate email addresses in a users table:

SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

The result shows each duplicated email and how many rows share it. If you want to see only the email addresses (without the count), you can omit the COUNT(*) from the select list, but keeping it is useful to gauge the severity.

Finding All Rows That Are Duplicates

The query above shows only the duplicate values, not the individual rows. To see every row that is part of a duplicate group, you need a self-join or a subquery. A common approach uses a subquery to get the duplicated keys, then joins back to the original table:

SELECT *
FROM your_table t1
INNER JOIN (
    SELECT column1, column2
    FROM your_table
    GROUP BY column1, column2
    HAVING COUNT(*) > 1
) t2
ON t1.column1 = t2.column1 AND t1.column2 = t2.column2;

This returns all rows that belong to any duplicate group. If the table has a primary key (e.g., id), you can also use EXISTS:

SELECT *
FROM your_table t1
WHERE EXISTS (
    SELECT 1 FROM your_table t2
    WHERE t1.column1 = t2.column1
      AND t1.column2 = t2.column2
      AND t1.id <> t2.id
);

The <> ensures that a row is not considered a duplicate of itself. Choose the method that feels clearest to you; both produce the same result.

Finding Duplicates on Multiple Columns

Sometimes uniqueness is defined by a combination of columns, not a single one. For example, an order line might be unique by order_id and product_id. Simply list all the columns in the GROUP BY clause:

SELECT order_id, product_id, COUNT(*)
FROM order_items
GROUP BY order_id, product_id
HAVING COUNT(*) > 1;

This treats rows as duplicates only if all listed columns match. If you want to find duplicates where any one of several columns matches, you would need to check each column separately or use a concatenated expression, but that is less common.

How to Delete Duplicates (Safely)

Once you have identified duplicates, you usually want to remove them while keeping one representative row. The safest way is to use a temporary table or a self-join with a primary key. Here is a standard method that keeps the row with the smallest id for each duplicate group:

DELETE t1 FROM your_table t1
INNER JOIN your_table t2
    ON t1.column1 = t2.column1
   AND t1.column2 = t2.column2
   AND t1.id > t2.id;

This deletes every row that has a larger id than another row with the same duplicate key, leaving exactly one row per group. If your table does not have a primary key, you can create a temporary table with distinct rows and then replace the original:

CREATE TABLE temp_table AS
SELECT DISTINCT * FROM your_table;

DROP TABLE your_table;
RENAME TABLE temp_table TO your_table;

Be careful: this removes all duplicates and keeps only distinct rows, but it also drops indexes and foreign keys. You will need to recreate them. Always back up your data before running any delete operation.

Using a Unique Index to Prevent Future Duplicates

After cleaning the data, the best way to prevent duplicates is to add a unique constraint on the columns that should be unique. For example:

ALTER TABLE your_table
ADD UNIQUE INDEX idx_unique (column1, column2);

If you already have duplicates, this command will fail. You must remove the duplicates first. Once the unique index is in place, any attempt to insert a duplicate row will result in an error, which your application can catch and handle gracefully.

Common Mistakes and Pitfalls

  • Forgetting HAVING vs WHERE: You cannot use WHERE COUNT(*) > 1 because WHERE filters rows before grouping. Use HAVING after GROUP BY.
  • Including the primary key in the GROUP BY: If you group by id, every row is unique, so no duplicates will be found. Group only by the columns that define a duplicate.
  • Case sensitivity: MySQL string comparisons are case-insensitive by default (depending on collation). If you need case-sensitive duplicate detection, use BINARY or a case-sensitive collation.
  • NULL values: NULL values are not considered equal to each other in GROUP BY (they form their own group). If your column contains NULL, two rows with NULL will not be flagged as duplicates by the standard query.

Frequently Asked Questions

How do I find duplicates in MySQL without GROUP BY?

You can use a self-join with EXISTS or IN. For example, SELECT * FROM your_table t1 WHERE EXISTS (SELECT 1 FROM your_table t2 WHERE t1.email = t2.email AND t1.id <> t2.id); This returns all rows that have at least one other row with the same email. It is equivalent to the GROUP BY method but can be easier to read when you want the full rows.

How do I delete all duplicates except one?

Use the self-join delete with a primary key: DELETE t1 FROM your_table t1 INNER JOIN your_table t2 ON t1.email = t2.email AND t1.id > t2.id; This keeps the row with the smallest id for each duplicate group. If you want to keep the newest row, change > to <.

Can I find duplicates in MySQL using ROW_NUMBER()?

Yes, MySQL 8.0 and later support window functions. You can use ROW_NUMBER() OVER (PARTITION BY column1, column2 ORDER BY id) AS rn and then filter for rn > 1 to see duplicates. This is especially useful when you want to keep a specific row (e.g., the newest) and delete the rest.

Why does my duplicate query return nothing even though I see duplicates?

Check whether you are grouping by the correct columns. If you accidentally include a column that is unique per row (like a primary key), the query will not find duplicates. Also, check for NULL values: MySQL treats NULL as distinct in GROUP BY, so rows with NULL in the key column will not be grouped together.

Is it safe to delete duplicates directly?

It is safe only if you have a backup and you are certain which rows you want to keep. Always run a SELECT query first to see exactly which rows will be deleted. Test the delete on a copy of the table if possible. Deleting data is irreversible without a backup.