The safest way to find and delete duplicate rows in SQL is to first inspect duplicates with a SELECT using GROUP BY or ROW_NUMBER(), back up or stage the affected rows, test inside a transaction (BEGIN TRANSACTION / ROLLBACK), and delete extra copies using a Common Table Expression (CTE) with ROW_NUMBER() (or a primary key / ctid / TID identifier). Always define which columns make two rows “duplicates” and which copy you want to keep (such as the lowest ID or latest timestamp).
1. Find Duplicate Rows First (GROUP BY and HAVING)
Before deleting anything, verify what counts as a duplicate and see how many extra rows exist.
SELECT
email,
COUNT(*) AS duplicate_count,
MIN(id) AS keep_id,
MAX(id) AS latest_id
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
GROUP BYgroups rows sharing the same logical key (here,email).HAVING COUNT(*) > 1filters to keys that appear more than once.
2. Inspect the Exact Rows That Will Be Deleted (ROW_NUMBER())
ROW_NUMBER() assigns a sequential number (1, 2, 3...) within each duplicate group. Keeping row_num = 1 and deleting row_num > 1 is clean and predictable.
WITH ranked_users AS (
SELECT
id,
email,
created_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at ASC, id ASC
) AS row_num
FROM users
)
SELECT id, email, created_at, row_num
FROM ranked_users
WHERE row_num > 1
ORDER BY email, row_num;
PARTITION BY emaildefines the duplicate group.ORDER BY created_at ASC, id ASCchooses which record stays asrow_num = 1(earliestcreated_at, breaking ties by smallestid).
3. Back Up Candidate Rows or the Target Table
Protect your data before modifying rows in place, especially in production environments:
-- Option A: Save a backup copy of the whole table (syntax varies slightly by RDBMS)
CREATE TABLE users_backup_20261130 AS
SELECT * FROM users;
-- Option B: Save only the rows targeted for deletion so you can restore them if needed
CREATE TABLE users_duplicates_removed AS
WITH ranked_users AS (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at ASC, id ASC
) AS row_num
FROM users
)
SELECT *
FROM ranked_users
WHERE row_num > 1;
4. Delete Duplicates Safely Inside a Transaction
Run the delete inside a transaction so you can check the affected row count and ROLLBACK if anything looks unexpected before committing.
PostgreSQL, SQL Server, and SQLite (CTE with ROW_NUMBER())
BEGIN TRANSACTION;
WITH ranked_users AS (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at ASC, id ASC
) AS row_num
FROM users
)
DELETE FROM users
WHERE id IN (
SELECT id
FROM ranked_users
WHERE row_num > 1
);
-- Inspect remaining rows or counts before committing:
-- SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
COMMIT;
-- Or run ROLLBACK; if the result is not what you expected.
MySQL (Self-Join Delete Keeping Smallest id)
MySQL has restrictions on selecting from the same table being updated/deleted in a subquery; a multi-table DELETE with a self-join avoids that limitation:
START TRANSACTION;
DELETE u2
FROM users AS u1
JOIN users AS u2
ON u1.email = u2.email
AND u1.id < u2.id;
-- Verify results, then:
COMMIT;
-- Or ROLLBACK;
5. Prevent Duplicates From Coming Back
Once cleanup is verified, enforce uniqueness at the database level so new duplicates cannot slip in:
ALTER TABLE users
ADD CONSTRAINT uq_users_email UNIQUE (email);
Safety Checklist
- Confirm the duplicate key: Decide whether duplicates mean matching one column (like
email) or a combination of columns (likefirst_name, last_name, birth_date). - Define the survivor rule: Explicitly order by a deterministic column (timestamp or ID) so
row_num = 1is consistent. - Check foreign keys: If other tables reference the rows you plan to delete, verify foreign key constraints or cascading rules first.
- Test on a small batch or transaction: Check
SELECTcounts beforeDELETE, and confirm zeroHAVING COUNT(*) > 1rows remain afterward.
