Deduplication with an explicit survivor rule
Overview
Deduplication starts by defining a business key and deciding which record survives. Here a non-null contact_key identifies a contact, and the most recent updated_at wins; higher id breaks equal timestamps. These are read-only previews, not DELETE statements.
First example
SELECT contact_key, COUNT(*) AS n FROM analytics_contacts GROUP BY contact_key HAVING COUNT(*) > 1 ORDER BY contact_key;Observed SQLite result (rows in JSON):
[ [ "A", 3 ]]How it works
GROUP BY reveals repeated business keys and COUNT(*) measures their multiplicity. ROW_NUMBER selects a single survivor per key even when timestamps tie. DISTINCT on entire rows cannot remove logical duplicates with different IDs. If a key may be NULL, decide whether missing keys can identify the same entity before grouping.
Practical example
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY contact_key ORDER BY updated_at DESC, id DESC) AS rn FROM analytics_contacts)SELECT contact_key, id, updated_at FROM ranked WHERE rn = 1 ORDER BY contact_key;Observed SQLite result (rows in JSON):
[ [ "A", 3, "2025-01-02 09:00:00" ], [ "B", 4, "2025-01-01 10:00:00" ]]Practice and mistakes
Change the tie-breaker to id ASC and predict the winning record for key A (2 instead of 3). Before any production deletion, review survivor rules and dependencies, use an authorized migration and enforce the intended uniqueness constraint. No source rows are changed here.