How to Delete Duplicate Rows in SQL (and Keep the Right One)

8 min read

To delete duplicate rows in SQL, keep one row from each group of duplicates and delete the rest: DELETE FROM leads WHERE lead_id NOT IN (SELECT MIN(lead_id) FROM leads GROUP BY email) keeps the first row for each email and removes every later copy. To keep the latest copy instead, number the rows in each group with ROW_NUMBER() and delete every row numbered above 1.

Both methods need a column that tells copies apart, usually an ID. If the duplicates are identical in every column, you need a hidden row identifier or a rebuilt table, both covered below. Before any of that, though, comes the step most people skip: deciding what “duplicate” means for this table, and checking what you are about to delete.

The methods at a glance

Each row below is a way to remove duplicates, the situation it suits, and the key statement. The examples refer to the leads table introduced in the next section.

Method Use when Key statement Works in
MIN or MAX id with NOT IN The table has a unique id and you keep the first or last inserted copy DELETE FROM leads WHERE lead_id NOT IN (SELECT MIN(lead_id) FROM leads GROUP BY email) PostgreSQL, SQL Server, SQLite; MySQL with a wrapper
Self-join DELETE MySQL, keeping the lowest id DELETE l1 FROM leads l1 JOIN leads l2 ON l1.email = l2.email AND l1.lead_id > l2.lead_id MySQL
ROW_NUMBER You choose which copy survives by another column, such as latest date ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC), then delete rn > 1 All four, MySQL from 8.0
Hidden row id Rows are identical in every column, no id rowid (SQLite), ctid (PostgreSQL) SQLite, PostgreSQL
Rebuild with DISTINCT Identical rows, any database, or a huge share of duplicates CREATE TABLE new AS SELECT DISTINCT …, then swap All

The data used throughout

A Gurugram fintech collects personal loan enquiries through a web form. A bug in the form’s submit button sent some enquiries twice, and some applicants came back days later and filled the form again. The sales team is now calling the same people more than once. Loan amounts are in rupees.

lead_id email city loan_amount created_at
1 [email protected] Gurugram 300000 2026-11-01 10:02
2 [email protected] Delhi 500000 2026-11-01 10:15
3 [email protected] Gurugram 300000 2026-11-01 10:02
4 [email protected] Noida 200000 2026-11-02 09:40
5 [email protected] Delhi 500000 2026-11-01 10:16
6 [email protected] Gurugram 750000 2026-11-02 11:05
7 [email protected] Gurugram 300000 2026-11-03 18:20
8 [email protected] Noida 250000 2026-11-04 12:00

Notice that no two rows are identical: every row has its own lead_id, and some copies differ in time or amount. Duplicates in real data almost always look like this. That is why the first decision is which columns define a duplicate. Here the business answer is one lead per email address.

Step 1: find the duplicates

Group by the columns that define a duplicate and keep groups with more than one row. This changes nothing, so run it freely.

Part SQL
Group by the duplicate key SELECT email, COUNT(*) AS copies FROM leads GROUP BY email
Keep only repeated groups HAVING COUNT(*) > 1 ORDER BY email
email copies
[email protected] 2
[email protected] 2
[email protected] 3

Three emails are duplicated, and the table has 4 extra rows (one extra each for Arjun and Meera, two for Riya). After the clean-up it should hold 4 rows, one per email. Write that number down; it is your check at the end. If GROUP BY and HAVING are new to you, our lesson on GROUP BY and HAVING in SQL covers them.

Step 2: decide which copy to keep, and preview

Look at the copies before deleting anything. Riya’s leads 1 and 3 are identical, the double-click bug. Arjun’s 2 and 5 are a minute apart. But Meera’s are different: lead 4 asked for 2,00,000 rupees and lead 8, two days later, asked for 2,50,000. If you keep the first copy, the sales team calls Meera about the wrong amount.

So there are two reasonable rules, and they give different results:

Rule Keeps Meera’s surviving amount
Keep the first enquiry (lowest lead_id) Leads 1, 2, 4, 6 200000
Keep the latest enquiry (newest created_at) Leads 5, 6, 7, 8 250000

This is a business decision, not a SQL one. For a sales team, the latest enquiry is usually right. For attribution (“which campaign brought this lead in?”), the first one is. Ask before you delete.

Method 1: keep the first copy with MIN

The subquery finds the lowest lead_id for each email. Every row whose id is not in that list is a later copy.

Preview first, by running the same condition as a SELECT:

Part SQL
Preview SELECT * FROM leads
Rows that are not the first copy WHERE lead_id NOT IN (SELECT MIN(lead_id) FROM leads GROUP BY email)

That returns leads 3, 5, 7 and 8, the four extra rows Step 1 predicted. Now change SELECT * to DELETE:

Part SQL
Delete DELETE FROM leads
Same condition WHERE lead_id NOT IN (SELECT MIN(lead_id) FROM leads GROUP BY email)
lead_id email city loan_amount created_at
1 [email protected] Gurugram 300000 2026-11-01 10:02
2 [email protected] Delhi 500000 2026-11-01 10:15
4 [email protected] Noida 200000 2026-11-02 09:40
6 [email protected] Gurugram 750000 2026-11-02 11:05

Four rows, one per email, as predicted. Use MAX instead of MIN to keep the last inserted copy.

This exact statement works in PostgreSQL, SQL Server and SQLite. NOT IN is safe here because MIN(lead_id) never returns NULL when lead_id is a primary key; on a nullable column, NOT IN can return nothing at all, a trap our lesson on subqueries in SQL explains.

The MySQL error 1093 and its fixes

Run the same DELETE in MySQL and it fails with error 1093: “You can’t specify target table ‘leads’ for update in FROM clause”. MySQL does not let a DELETE read from the table it is deleting from in a subquery. There are two standard fixes.

Fix SQL (MySQL)
Wrap the subquery in a derived table DELETE FROM leads WHERE lead_id NOT IN (SELECT keep_id FROM (SELECT MIN(lead_id) AS keep_id FROM leads GROUP BY email) AS k)
Or use a self-join DELETE DELETE l1 FROM leads l1 JOIN leads l2 ON l1.email = l2.email AND l1.lead_id > l2.lead_id

The extra layer in the first fix makes MySQL build the list of IDs to keep before it starts deleting. The self-join deletes every row for which a lower lead_id with the same email exists, which leaves exactly the lowest one. Flip the greater-than to less-than to keep the highest instead.

Method 2: keep the latest copy with ROW_NUMBER

When the rule is “keep the newest”, MIN and MAX on the id are not reliable: ids usually follow insert order, but a backfilled or imported row can break that. ROW_NUMBER lets you rank the copies by whatever column defines “best”, and ROW_NUMBER is the right function here rather than RANK, because it never gives two rows the same number. Our lesson on SQL window functions explains the three ranking functions in full.

Numbering the copies within each email, newest first:

Part SQL
Number the copies SELECT lead_id, email, created_at, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, lead_id DESC) AS rn FROM leads
lead_id email created_at rn
5 [email protected] 2026-11-01 10:16 1
2 [email protected] 2026-11-01 10:15 2
6 [email protected] 2026-11-02 11:05 1
8 [email protected] 2026-11-04 12:00 1
4 [email protected] 2026-11-02 09:40 2
7 [email protected] 2026-11-03 18:20 1
3 [email protected] 2026-11-01 10:02 2
1 [email protected] 2026-11-01 10:02 3

Every row with rn above 1 goes. Riya’s leads 1 and 3 have the same timestamp, which is why lead_id DESC is in the ORDER BY as a tie-breaker. Without it, which of the two gets rn 2 is up to the database, and running the same query twice could keep different rows.

The delete itself is written differently in each database:

Database Delete rows with rn above 1
SQL Server WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, lead_id DESC) AS rn FROM leads) DELETE FROM ranked WHERE rn > 1
PostgreSQL and SQLite DELETE FROM leads WHERE lead_id IN (SELECT lead_id FROM (SELECT lead_id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, lead_id DESC) AS rn FROM leads) AS ranked WHERE rn > 1)
MySQL 8.0 DELETE l FROM leads l JOIN (SELECT lead_id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, lead_id DESC) AS rn FROM leads) AS ranked ON l.lead_id = ranked.lead_id WHERE ranked.rn > 1

SQL Server’s version is the neatest, because it lets you delete straight from a CTE, and the delete flows through to the table. Our CTE in SQL lesson covers the WITH clause. After the delete, the table holds leads 5, 6, 7 and 8: four rows, one per email, with Meera’s newer 2,50,000 request kept.

Method 3: rows identical in every column, with no id

Data loaded from CSV files often has no id column at all, and the duplicates are exact copies. There is nothing in the row to tell copy one from copy two, so you need something outside the visible columns.

Database Approach
SQLite Every table has a hidden rowid: DELETE FROM raw_leads WHERE rowid NOT IN (SELECT MIN(rowid) FROM raw_leads GROUP BY email, city, loan_amount)
PostgreSQL Each row has a hidden physical address, ctid: DELETE FROM raw_leads a USING raw_leads b WHERE a.ctid > b.ctid AND a.email = b.email AND a.city = b.city AND a.loan_amount = b.loan_amount
SQL Server The ROW_NUMBER CTE above works without an id; use PARTITION BY on every column and ORDER BY (SELECT NULL)
MySQL Add an id first with ALTER TABLE raw_leads ADD id INT AUTO_INCREMENT PRIMARY KEY, then use Method 1; or rebuild the table

The rebuild works in any database: CREATE TABLE leads_clean AS SELECT DISTINCT * FROM raw_leads, check its row count, then drop the old table and rename the new one. It is also the fastest route when a large share of a big table is duplicated, because writing the 30% you keep is cheaper than deleting the 70% you do not. The catch is that CREATE TABLE AS does not copy indexes, keys or permissions, so recreate them. Our DDL commands in SQL lesson covers the CREATE, DROP and RENAME statements involved.

Note that SELECT DISTINCT on its own removes nothing from the table. It only hides duplicates in that one query’s output. Analysts often use it as a quick fix in a report, which is fine, but the duplicates are still there for the next person.

Stop duplicates coming back

Deleting duplicates without fixing the cause means doing it again next month. Once the table is clean, add a unique constraint on the column that defines a duplicate:

Step SQL
Enforce one row per email CREATE UNIQUE INDEX ux_leads_email ON leads (email)
A repeat insert now fails INSERT INTO leads (email, city, loan_amount, created_at) VALUES (‘[email protected]’, ‘Gurugram’, 300000, ‘2026-11-05 09:00’)

The second statement fails with a unique constraint error, which is the point. The application can then decide what to do with a repeat: MySQL has INSERT IGNORE and ON DUPLICATE KEY UPDATE, PostgreSQL and SQLite have ON CONFLICT DO NOTHING or DO UPDATE, and SQL Server uses MERGE. The unique index can only be created after the duplicates are gone, which is another reason the order of work is find, clean, then constrain. Our lesson on primary keys and foreign keys in SQL covers unique constraints alongside the other keys.

A safe routine for any duplicate delete

DELETE cannot be undone once committed, so this is worth doing every time:

  1. Count the duplicates with GROUP BY and HAVING, and work out how many rows should remain.
  2. Copy the table: CREATE TABLE leads_backup AS SELECT * FROM leads.
  3. Run the DELETE’s WHERE clause as a SELECT and check the rows.
  4. Run the DELETE inside a transaction, check the row count, and only then COMMIT.
  5. Add a unique constraint so it cannot happen again.

Frequently asked questions

How do I delete duplicate rows in SQL but keep one?

Group rows by the columns that define a duplicate, find the one row per group to keep (for example with MIN of the id column), and delete every row not in that list. A common form is DELETE FROM table WHERE id NOT IN (SELECT MIN(id) FROM table GROUP BY duplicate_columns). To choose the surviving row by date or another column, use ROW_NUMBER and delete rows numbered above 1.

How do I find duplicate records in SQL?

Use GROUP BY on the columns that should be unique and HAVING COUNT(*) > 1, such as SELECT email, COUNT(*) FROM leads GROUP BY email HAVING COUNT(*) > 1. This lists each duplicated value and how many copies exist. To see the full rows, select from the table where the column is in that list.

Why does MySQL give error 1093 when deleting duplicates?

MySQL does not allow a DELETE or UPDATE to select from the same table in a subquery, and raises error 1093. Wrap the subquery in a derived table, so MySQL materialises the list first, or use a self-join DELETE such as DELETE l1 FROM leads l1 JOIN leads l2 ON l1.email = l2.email AND l1.lead_id > l2.lead_id.

How do I delete duplicates without a primary key?

Use a hidden row identifier if your database has one: rowid in SQLite or ctid in PostgreSQL. In SQL Server, delete from a CTE that numbers rows with ROW_NUMBER partitioned by every column. In MySQL, add an auto-increment column first, or rebuild the table with SELECT DISTINCT and swap it in.

Does SELECT DISTINCT remove duplicates from a table?

No. SELECT DISTINCT removes duplicate rows only from that query’s result; the table itself is unchanged. To remove them permanently, use DELETE with one of the methods above, or create a new table from SELECT DISTINCT and replace the old one.

How can I prevent duplicate rows in SQL?

Add a UNIQUE constraint or unique index on the columns that define a duplicate, after cleaning the existing duplicates. The database then rejects repeat inserts. Combine it with INSERT IGNORE or ON DUPLICATE KEY UPDATE in MySQL, ON CONFLICT in PostgreSQL and SQLite, or MERGE in SQL Server to handle repeats gracefully.

Clean data is most of the job

Duplicate leads, double-counted orders and repeated customer records are among the first problems a new analyst is handed, and also a standard interview question; our SQL interview questions include it. Fixing them safely is mostly about checking before you change anything.

SkilloVilla’s SQL: Beginner to Advanced course covers the fundamental statements, aggregation, joins and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. If you want SQL as part of a full analyst programme with Excel, Python, Power BI and placement support, see the Data Analytics with Python track.

Statistics for Data Analytics: The Topics an Analyst Needs,…

Statistics for data analytics: the topics an analyst uses, grouped into a learning path, with the business question each answers and a study plan.
SkilloVilla Team
6 min read

Standard Deviation and Variance for Data Analysts, With Worked…

Standard deviation and variance for data analysts: population vs sample (n vs n-1), a worked calculation, Excel and SQL functions, and what it means.
SkilloVilla Team
7 min read

Power BI vs Tableau: Which to Learn for an…

Power BI vs Tableau compared for Indian job-seekers: job demand, cost, learning curve, data prep, Mac support and sharing, with a side-by-side table.
SkilloVilla Team
5 min read

Leave a Reply