Interview question
Remove duplicate imports while keeping the newest row
Ranks duplicate import rows, previews the deletion set, and removes older copies with deterministic retention.
TL;DR
Ranks duplicate import rows, previews the deletion set, and removes older copies with deterministic retention.
ROW_NUMBER cleanup, deterministic retention, preview-first safety, transactions, and follow-up uniqueness enforcement.
Practice the problem like a real interview: restate, reason, implement, and test.
Table: ImportedOrders(ImportRowId, SourceSystem, ExternalId, ImportedAtUtc, PayloadHash). A duplicate is a repeated (SourceSystem, ExternalId). Keep the newest timestamp, breaking ties with the largest ImportRowId. First produce a preview query, then show the transactional delete.
Three rows share source ERP and external id A-42. The newest timestamp is kept. If two newest timestamps tie, the larger import row id survives.
I rank rows inside each business key, newest first, and treat rows after rank one as duplicates. I run the CTE as a SELECT first and reconcile counts. The same ranking expression is then used by the delete inside a transaction. The cleanup is incomplete until the write path becomes idempotent and the database enforces the intended key where possible.
-- Preview first.
WITH RankedImports AS
(
SELECT
i.ImportRowId,
i.SourceSystem,
i.ExternalId,
i.ImportedAtUtc,
ROW_NUMBER() OVER
(
PARTITION BY i.SourceSystem, i.ExternalId
ORDER BY i.ImportedAtUtc DESC, i.ImportRowId DESC
) AS rn
FROM dbo.ImportedOrders AS i
)
SELECT ImportRowId, SourceSystem, ExternalId, ImportedAtUtc
FROM RankedImports
WHERE rn > 1
ORDER BY SourceSystem, ExternalId, rn;
-- Execute only after the preview is reviewed and backed up.
BEGIN TRANSACTION;
WITH RankedImports AS
(
SELECT
i.ImportRowId,
ROW_NUMBER() OVER
(
PARTITION BY i.SourceSystem, i.ExternalId
ORDER BY i.ImportedAtUtc DESC, i.ImportRowId DESC
) AS rn
FROM dbo.ImportedOrders AS i
)
DELETE FROM RankedImports
OUTPUT deleted.ImportRowId
WHERE rn > 1;
-- Reconcile the output and remaining duplicate count before COMMIT.
COMMIT TRANSACTION;
The ranking sorts rows by business key and retention order. A supporting index on (SourceSystem, ExternalId, ImportedAtUtc DESC, ImportRowId DESC) reduces sort work. Large cleanup jobs should be batched to control log growth and lock duration.
ExternalId but come from different source systems.Move to the linked follow-up, next path step, prerequisite, or deeper variant.
Practice the next layer of the same subject.