How would you identify and resolve duplicate records in a database table?

Instruction: Explain the steps you would take to find and remove duplicates from a table.

Context: This question evaluates the candidate's problem-solving skills and their ability to write efficient SQL queries to maintain data integrity by identifying and eliminating duplicate records.

Updated

Official answer

Define what counts as duplicate and which facts must be preserved. Equal names alone do not establish the same entity. For a hypothetical rule that each non-NULL email should appear once, first inspect candidate rows in PostgreSQL users(user_id integer PRIMARY KEY, email text):

WITH ranked AS (
  SELECT user_id, email,
         ROW_NUMBER() OVER (PARTITION BY email ORDER BY user_id) AS position
  FROM users
  WHERE email IS NOT NULL
)
SELECT user_id, email
FROM ranked
WHERE position > 1
ORDER BY email, user_id;

This deterministically identifies extra rows under a keep-lowest-ID rule; it does not prove that is the correct survivor. Comparison semantics determine whether differently cased emails match.

Review conflicting attributes and child references, choose an authoritative merge policy, and preserve the evidence needed for recovery. Apply reviewed merges/deletions in a transaction with exact identity/state checks and protection against concurrent duplicate creation. Reconcile counts and relationships afterward. A uniqueness constraint can prevent recurrence only after its NULL and canonicalization rules match the business requirement. Avoid blanket deletion based on an arbitrary row number.

Related Questions