Quick revision
The short answer
To list duplicates we group by lower(email) and keep groups with HAVING COUNT(*) > 1. To delete them we number the rows in each lower(email) group with ROW_NUMBER() ordered by id and delete every row numbered above 1, after repointing child rows such as orders to the kept id. To prevent new duplicates we add a unique index on lower(email) in PostgreSQL, or on a normalized generated column in MySQL, and normalize emails in the application too.
What to remember
In this answer, we found duplicated emails with GROUP BY lower(email) HAVING COUNT(*) > 1, and deleted the extras by numbering each group with ROW_NUMBER() ordered by id and removing rows numbered above 1, or with PostgreSQL's DELETE ... USING self join. MySQL rejects a subquery on the target table with error 1093 unless it is wrapped in a derived table, or we use a multi-table DELETE. We repointed child rows to the kept id first, so foreign keys neither block the delete nor cascade it into lost orders, and prevented new duplicates with a unique index on lower(email) or citext in PostgreSQL, a unique index on a normalized generated column in MySQL, and normalization in the application.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
To list duplicates we group by lower(email) and keep groups with HAVING COUNT(*) > 1. To delete them we number the rows in each lower(email) group with ROW_NUMBER() ordered by id and delete every row numbered above 1, after repointing child rows such as orders to the kept id. To prevent new duplicates we add a unique index on lower(email) in PostgreSQL, or on a normalized generated column in MySQL, and normalize emails in the application too.
Why this question is asked
Duplicate sign-ups are one of the most common data problems in any application with a registration form. Someone signs up as Ana@Example.com, forgets, and signs up again as ana@example.com. Now they get two newsletters, their orders are split across two accounts, and password reset finds the wrong one. Interviewers ask this coding question because it covers finding, deleting and preventing duplicates, and because a careless delete can lose real data. In this answer, we will set up the data, find the duplicates, delete them with a window function and with a self join, deal with child rows, look at MySQL's restriction on deleting from the same table, and finally stop duplicates for good.
1Setting Up the Data
Our table has an id generated by a sequence, the email as typed, and the sign-up time. Three rows belong to the same person, written with different letter case.
An email address's domain part is not case sensitive, and in practice almost no mail provider treats the local part (before the @) as case sensitive either. So for this business, two emails that differ only in case belong to the same customer, and we compare them with lower(email).
2Finding the Duplicated Emails
We group by the normalized email and keep only groups with more than one row. HAVING filters groups after aggregation, the way WHERE filters rows before it.
Adding MIN(id) shows which row we are going to keep. Before any delete, it is worth running this on production and looking at a few groups by hand: sometimes two "duplicates" are a shared family address, and the business may want to keep both.
3Deleting the Duplicates With ROW_NUMBER
ROW_NUMBER() OVER (PARTITION BY lower(email) ORDER BY id) numbers the rows within each email group, starting at 1 for the lowest id. Every row with a number above 1 is a duplicate. We cannot use a window function directly in a DELETE's WHERE clause, so we compute the numbers in a subquery and delete by id.
| id | lower(email) | rn | action |
|---|---|---|---|
| 1 | ana@example.com | 1 | keep |
| 3 | ana@example.com | 2 | delete, repoint children to 1 |
| 4 | ana@example.com | 3 | delete, repoint children to 1 |
| 2 | ben@example.com | 1 | keep |
In PostgreSQL there is also a shorter form with a self join: DELETE ... USING joins the table to itself and deletes every row for which a row with the same normalized email and a lower id exists.
4The Self Join Version and MySQL's Error 1093
The self join form reads naturally: delete a where there is a b with the same email and a smaller id.
MySQL refuses to read from the table it is deleting from in a plain subquery, which is error 1093. Wrapping the subquery in a derived table, the FROM (...) t part, works because MySQL builds that result first and then deletes. The multi-table DELETE is MySQL's equivalent of PostgreSQL's USING.
5Repointing Child Rows Before Deleting
There is a catch that turns a cleanup into an incident. Customer 3 may have orders and addresses. If those tables have a foreign key without cascade, the delete fails. If they have ON DELETE CASCADE, the delete succeeds and silently removes the customer's orders. Either way, the right thing is to move the children to the kept customer first, in the same transaction.
Notice that one mapping table drives every step, so the children and the delete always agree on which row survives. If the kept row and a duplicate both have an address marked as default, we may also need a rule for that, which is a business decision.
6Preventing New Duplicates
Cleaning up is pointless if the form keeps creating duplicates. In PostgreSQL, a unique index on the expression lower(email) refuses a second row whose lowercased email already exists. Alternatively, the citext extension provides a case-insensitive text type, and a plain unique constraint on a citext column does the same. In MySQL we can add a normalized generated column and put the unique index on it.
In MySQL, also check the column's collation: with the default utf8mb4_0900_ai_ci, comparisons are already case-insensitive, so a plain unique index on email would also reject case variants. We still normalize in the application, trimming spaces and lowercasing before saving, so that what we store is clean and the database constraint is a safety net that a race between two sign-ups cannot get past.
7Follow-up questions
How would you pick the row to keep if the newest one has the better data?
Change the ORDER BY in the window: order by a quality score, such as verified email first, then the most recent login, and keep rn = 1. Often the best answer is to merge instead: copy the better fields from the duplicates into the kept row with an UPDATE before deleting, so we keep the oldest id that other systems reference but the newest data.
Why not just add the unique index first?
Because creating a unique index fails while duplicates exist. We clean first, then add the index, ideally with CREATE UNIQUE INDEX CONCURRENTLY on a live table, and the application handles the duplicate key error with a friendly message.
Is lower() enough to normalize an email?
It handles case, and trim() handles spaces. Rules such as ignoring dots in some providers' local parts are provider specific and risky, so most systems stop at case and whitespace.
8Conclusion
In this answer, we found duplicated emails with GROUP BY lower(email) HAVING COUNT(*) > 1, and deleted the extras by numbering each group with ROW_NUMBER() ordered by id and removing rows numbered above 1, or with PostgreSQL's DELETE ... USING self join. MySQL rejects a subquery on the target table with error 1093 unless it is wrapped in a derived table, or we use a multi-table DELETE. We repointed child rows to the kept id first, so foreign keys neither block the delete nor cascade it into lost orders, and prevented new duplicates with a unique index on lower(email) or citext in PostgreSQL, a unique index on a normalized generated column in MySQL, and normalization in the application.
Open with
To list them I group by lower of email, having count greater than one, and I add min id so I can see which row we will keep.
Then, if they want more
To delete, I number the rows with ROW_NUMBER over partition by lower email order by id, and delete the ids where the number is greater than one, from a subquery since window functions cannot be used directly in WHERE.
In PostgreSQL I could also write delete from customer a using customer b where the lowered emails match and a.id is greater than b.id. MySQL refuses a subquery on the same table in DELETE, error 1093, so there I wrap it in a derived table or use a multi-table delete with a self join.
The important step before any delete is the child rows. Orders and addresses of the duplicates must be repointed to the kept id in the same transaction, otherwise the delete fails on a foreign key, or worse, cascades and removes real orders. I would drive that from one mapping table of duplicate id to kept id.
To prevent new duplicates, in PostgreSQL I add a unique index on lower of email, or use citext; in MySQL a unique index on a stored generated column with the normalized email, keeping in mind that MySQL's default collation is already case-insensitive. And the application trims and lowercases emails before saving, with the constraint as the safety net.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8.4
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Table customer(id bigserial primary key, email text, created_at timestamptz). Some...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/f51c23c3e6/