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
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
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.