Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users GROUP BY email);
SELECT * FROM users ORDER BY id;| id | |
|---|---|
| 1 | a@x.com |
| 3 | b@x.com |
The subquery keeps one id per email (1 and 3); everything else goes. NOT IN is safe here because MIN(id) over a non-NULL id never returns NULL.
The window version is easier to adapt when "keep" means something else, such as the most recent row:
sql
CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO u2 VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM u2 WHERE id IN (
SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id DESC) AS rn FROM u2) WHERE rn > 1
);
SELECT * FROM u2 ORDER BY id;| id | |
|---|---|
| 3 | b@x.com |
| 4 | a@x.com |
Run the same logic as a SELECT first to see what will be deleted, then add the constraint:
text
CREATE UNIQUE INDEX users_email_unique ON users(email);Without that, the next import will create duplicates again. Watch case and spaces too: 'Ana@x.com' and 'ana@x.com ' count as different values unless normalized.
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users GROUP BY email);
SELECT * FROM users ORDER BY id;
CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO u2 VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM u2 WHERE id IN (
SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id DESC) AS rn FROM u2) WHERE rn > 1
);
SELECT * FROM u2 ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Keep MIN(id) per group and delete the rest
- ROW_NUMBER per group handles other keep rules
- Preview with SELECT before deleting
- Add a UNIQUE constraint afterwards
Common mistakes
- Deleting all copies including the one to keep
- Cleaning duplicates without preventing new ones
Follow-ups
- How would you keep the most recent row instead?
- How would you merge child rows that point at the deleted duplicates?
Tips
- Mention the follow-up constraint