Question presented to candidate:
"Our customers table was loaded from three different sign-up forms and we think some people are in it more than once. How would you find the duplicates with SQL, and what exactly counts as a duplicate?"
What a strong answer should cover:
- Define the duplicate first: which columns make two rows "the same" (here the email), since the surrogate
idis always unique - The core pattern:
GROUP BYthe key columns, thenHAVING COUNT(*) > 1to keep only groups with more than one row - Seeing the full duplicate rows, not just the keys: a window
COUNT(*) OVER (PARTITION BY ...), or a join/EXISTSback to the grouped keys - Dirty data: case and stray spaces (
LOWER(TRIM(email))), and thatGROUP BYputs all NULLs in one group even thoughNULL = NULLis not true - Engine detail: PostgreSQL and SQLite compare text case-sensitively by default, MySQL default collation does not
- Prevention: a
UNIQUEconstraint or unique expression index once the data is clean
Clarifying questions expected:
- Which columns define a duplicate: the whole row, or a business key like the email?
- Should
Asha@Example.comandasha@example.comcount as the same person? - Do you only want to report duplicates, or also remove them afterwards?
Code / implementation expected: Yes β a GROUP BY ... HAVING COUNT(*) > 1 query, plus one way to list the full duplicate rows.
Schema used by the examples: