Skip to the solution
EasyDSA9 min read

How do you find duplicate rows in a table?

694 views

The problem

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 id is always unique
  • The core pattern: GROUP BY the key columns, then HAVING COUNT(*) > 1 to 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/EXISTS back to the grouped keys
  • Dirty data: case and stray spaces (LOWER(TRIM(email))), and that GROUP BY puts all NULLs in one group even though NULL = NULL is not true
  • Engine detail: PostgreSQL and SQLite compare text case-sensitively by default, MySQL default collation does not
  • Prevention: a UNIQUE constraint 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.com and asha@example.com count 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:

  • duplicates
  • group-by

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 12 sections

Run the code

Edit the query and run it against the tables for this question.

SQLThe core pattern: group by the key, keep groups with more than one row
SQLEvery duplicate row in full, matching emails case- and space-insensitively
SQLDuplicates across several columns, with the ids in each group (SQLite GROUP_CONCAT)
SQLOnly the extra copies: rows that have an earlier row with the same email

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 8 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextEasy

When would you use a transaction explicitly?

Continue