Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

How would you identify duplicate rows to remove while deterministically keeping the newest record?

Answer

Rank rows inside each duplicate business-key group with ROW_NUMBER ordered from newest to oldest and add a stable tie-breaker such as the primary key. Treat rn = 1 as the survivor and rn > 1 as removal candidates. Preview those IDs first and perform any DELETE inside a controlled transaction.

Strong answer includes

  • uses ROW_NUMBER with PARTITION BY the real business key
  • uses deterministic ordering with a tie-breaker
  • previews candidate primary keys before destructive DML

Practical example

Solution · Deduplicate safely
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Rank each duplicate group; rn = 1 is the survivor and rn > 1 are removal candidates. ORDER BY must choose one deterministic survivor.

Expected result: Only primary keys that are safe candidates for review before deletion.

#sql#duplicates#window-functions#dml

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery