How would you use SQL to find duplicate business keys in a table?
Answer
Group by the business-key columns and filter groups with HAVING COUNT(*) greater than one, for example SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1. First define whether case, whitespace, NULL and historical versions should count as the same key. Then inspect the underlying rows, confirm the intended uniqueness rule and avoid deleting anything until ownership, retention and recovery are clear.
Strong answer includes
- uses GROUP BY with HAVING COUNT
- clarifies the real business key
- separates detection from destructive cleanup
Practical example
Runs against the resettable SQLite sample database used by the playground.
Run the query to see the result.
GROUP BY collapses rows to the business-key grain and HAVING filters after the count is calculated. Normalization makes the query match a rule where case and surrounding whitespace are insignificant.
Expected result: One row per duplicated normalized email, with the number of copies.