Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Table customer(id bigserial primary key, email text, created_at timestamptz). Some customers signed up twice with the same email, sometimes with different letter case. Write SQL to (a) list duplicated emails with their counts and (b) delete the duplicates, keeping the row with the lowest id. Then prevent new duplicates.

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.

SQL
CREATE TABLE customer (id bigserial PRIMARY KEY, email text, created_at timestamptz);
INSERT INTO customer (email, created_at) VALUES
('Ana@Example.com', '2026-01-03'), ('ben@example.com', '2026-01-04'),
('ana@example.com', '2026-02-10'), ('ANA@example.COM', '2026-03-01');
-- ids 1, 2, 3, 4: rows 1, 3 and 4 are the same customer

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.

SQL
SELECT lower(email) AS email, COUNT(*) AS copies, MIN(id) AS keep_id
FROM customer
GROUP BY lower(email)
HAVING COUNT(*) > 1;
-- ana@example.com | 3 | 1

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.

SQL
SELECT id, email, ROW_NUMBER() OVER (PARTITION BY lower(email) ORDER BY id) AS rn
FROM customer;
-- 1 | Ana@Example.com | 1 kept
-- 3 | ana@example.com | 2 duplicate
-- 4 | ANA@example.COM | 3 duplicate
-- 2 | ben@example.com | 1 kept
DELETE FROM customer
WHERE id IN (SELECT id FROM (
SELECT id, ROW_NUMBER() OVER (PARTITION BY lower(email) ORDER BY id) AS rn
FROM customer) t
WHERE rn > 1);
-- DELETE 2
Which row survives
idlower(email)rnaction
1ana@example.com1keep
3ana@example.com2delete, repoint children to 1
4ana@example.com3delete, repoint children to 1
2ben@example.com1keep

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.

SQL
-- PostgreSQL
DELETE FROM customer a
USING customer b
WHERE lower(a.email) = lower(b.email)
AND a.id > b.id;
-- DELETE 2
-- MySQL: a subquery on the same table is refused
DELETE FROM customer WHERE id IN (SELECT id FROM customer WHERE ...);
-- ERROR 1093: You can't specify target table 'customer' for update in FROM clause
-- MySQL: wrap it in a derived table, which MySQL materializes first
DELETE FROM customer WHERE id IN (
SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY lower(email) ORDER BY id) AS rn
FROM customer) t
WHERE rn > 1);
-- MySQL: or a multi-table DELETE with a self join
DELETE a FROM customer a JOIN customer b
ON lower(a.email) = lower(b.email) AND a.id > b.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.

Java
BEGIN;
CREATE TEMP TABLE dup_map AS
SELECT id AS dup_id, FIRST_VALUE(id) OVER (PARTITION BY lower(email) ORDER BY id) AS keep_id
FROM customer;
DELETE FROM dup_map WHERE dup_id = keep_id; -- only the duplicates remain
-- dup_id 3 -> keep_id 1, dup_id 4 -> keep_id 1
UPDATE orders o SET customer_id = m.keep_id FROM dup_map m WHERE o.customer_id = m.dup_id;
UPDATE address a SET customer_id = m.keep_id FROM dup_map m WHERE a.customer_id = m.dup_id;
DELETE FROM customer c USING dup_map m WHERE c.id = m.dup_id; -- DELETE 2
COMMIT;

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.

SQL
-- PostgreSQL
CREATE UNIQUE INDEX customer_email_uq ON customer (lower(email));
INSERT INTO customer (email) VALUES ('ANA@EXAMPLE.COM');
-- ERROR: duplicate key value violates unique constraint "customer_email_uq"
-- MySQL 8.4
ALTER TABLE customer
ADD COLUMN email_norm VARCHAR(255) AS (LOWER(TRIM(email))) STORED,
ADD UNIQUE INDEX customer_email_uq (email_norm);

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.

What to say in the interviewAbout 90 seconds aloud

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.
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/