QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Interview tasks

Task: remove duplicates, leaving one record each.

Duplicates are removed by numbering rows within groups with ROW_NUMBER() OVER (PARTITION BY …) and deleting everything numbered above one. The group is the normalised email, and a tie-break order decides which record stays. NULLs are excluded, because they sit in one group. A SELECT with the same condition is reviewed first, the delete then runs in a transaction with RETURNING, and counts are compared. Child references move to the kept record.

SQL · Tasks

Duplicates must go, with one record each kept. How not to delete too much?

Finding duplicates is easy, deleting them safely is harder: DELETE has no undo button, and a mistake in the condition touches live data. So the task is solved in three steps: number the rows in the groups, look at what will be deleted, and only then delete inside a transaction.

idemailcreated_at
1anna@x.io2026-01-10
2Anna@x.io2026-02-01
3oleh@x.io2026-01-15
4anna@x.io2026-03-01
5maria@x.io2026-03-02

How it works and why. ROW_NUMBER() OVER (PARTITION BY … ORDER BY …) numbers the rows inside each group without reducing their count (unlike GROUP BY). The group is the normalised email, and the order decides who becomes first: here the oldest by created_at with a tie-break on id. The row with number 1 stays, all with a number above 1 are extra copies. The tie-break is needed so that with equal dates the choice does not depend on chance.

Numbering and what is left after DELETE

ROW_NUMBER
idemailrn
1anna@x.io1
2Anna@x.io2 delete
3oleh@x.io1
4anna@x.io3 delete
5maria@x.io1
users after DELETE
idemail
1anna@x.io
3oleh@x.io
5maria@x.io
Figure 1. Number 1 is the one we keep. The order created_at, id makes the choice deterministic: always the oldest record.

Example: the safe sequence. First look at what exactly will be deleted (a SELECT with the same condition) and count the rows. Then, inside a transaction, delete returning the deleted rows, reconcile the counters and commit.

BEGIN;

WITH ranked AS (
  SELECT id,
         ROW_NUMBER() OVER (
           PARTITION BY LOWER(TRIM(email))
           ORDER BY created_at, id
         ) AS rn
  FROM users
  WHERE email IS NOT NULL
)
DELETE FROM users
WHERE id IN (SELECT id FROM ranked WHERE rn > 1)
RETURNING id, email;
-- 2 | Anna@x.io
-- 4 | anna@x.io

SELECT COUNT(*) FROM users;   -- 3
COMMIT;                       -- or ROLLBACK

The filter WHERE email IS NOT NULL is mandatory: for PARTITION BY all NULLs sit in one group, and without the filter every row with an empty email except the first would be deleted. RETURNING shows the deleted rows at once, BEGIN … COMMIT allows a rollback if the count does not match. The count is checked twice: before (5) and after (3), and the difference equals the number of rows with rn > 1 (2).

Limits and alternatives. The biggest risk is child records. If accounts reference the duplicate, a foreign key without a cascade will refuse the delete, and with ON DELETE CASCADE the related data vanishes together with the duplicate. Before deleting, references are moved to the kept record.

UPDATE accounts a
SET user_id = k.keep_id
FROM (
  SELECT id,
         FIRST_VALUE(id) OVER (
           PARTITION BY LOWER(TRIM(email))
           ORDER BY created_at, id
         ) AS keep_id
  FROM users
  WHERE email IS NOT NULL
) k
WHERE a.user_id = k.id AND k.id <> k.keep_id;

A simpler alternative when "the oldest" coincides with "the lowest id": DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users WHERE email IS NOT NULL GROUP BY LOWER(TRIM(email))). NOT IN is safe here because MIN(id) is never NULL, but the query would also delete the rows with an empty email, so the outer filter is needed too. On a shared environment make a copy of the table before deleting (CREATE TABLE users_backup AS SELECT * FROM users). After the cleanup the rule is enforced with a unique index, otherwise duplicates come back.

Common mistakes.

  • DELETE without a preceding SELECT and without a transaction: the mistake cannot be rolled back.
  • Not filtering NULL: all empty emails except one disappear.
  • Numbering without a tie-break in ORDER BY: which of the equal ones stays is down to chance.
  • Ignoring child records: an FK error or cascading deletion of related data.

Check yourself

The table has two users with email NULL. What happens if WHERE email IS NOT NULL is removed from the ROW_NUMBER query?

Answer

For PARTITION BY all NULLs share one group, so the second and later users without an email get rn above 1 and are deleted, although they are not duplicates. The delete should touch only real matches.

Accounts with ON DELETE CASCADE reference the duplicate. What happens when the duplicate is deleted and how to avoid it?

Answer

The user's accounts vanish with him. Before deleting, the accounts' user_id must be moved to the kept record (UPDATE with FIRST_VALUE), and only then the duplicates are deleted.

In an interview. Junior: I number the rows in each duplicate group with ROW_NUMBER and PARTITION BY and delete everything with a number above one. First a SELECT of the same rows, and everything runs inside a transaction. Middle/Senior: I add a tie-break to ORDER BY, exclude NULL and look at child records: I move the references to the kept record, otherwise foreign keys refuse the delete or a cascade destroys related data. After cleanup I enforce uniqueness with an index.

More articles in this chapter