lesson 50 Advanced product analysis · advanced
Deduplicate event retries
Identify repeated events and keep a consistent record.
the idea
Ingestion retries can produce several physical rows for one logical event. Define the event key and which version wins. ROW_NUMBER per event_key, ordered by ingested_at and id descending, keeps the latest version.
tables in this lesson
The challenges use this data. Each column shows its type underneath; → marks a link to another table.
social_events6 columns · 22 rows
| idinteger · key | event_keytext | member_idinteger | event_typetext | event_attext | ingested_attext |
|---|---|---|---|---|---|
| 1 | a | 1 | view | 2025-01-01 10:00:00 | 2025-01-01 10:00:01 |
| 2 | b | 1 | signup | 2025-01-01 10:03:00 | 2025-01-01 10:03:01 |
| 3 | c | 1 | purchase | 2025-01-01 10:05:00 | 2025-01-01 10:05:01 |
| 4 | a | 1 | view | 2025-01-01 10:00:00 | 2025-01-01 10:10:00 |
| 5 | d | 2 | view | 2025-01-02 09:00:00 | 2025-01-02 09:00:01 |
showing 5 of 22 rows
example
The idea in one query. Press Run to see what it returns; running examples never affects your progress.
WITH ranked AS(
SELECT
*,
ROW_NUMBER() OVER( PARTITION BY event_key ORDER BY ingested_at DESC,id DESC ) AS rn
FROM social_events
)
SELECT id,event_key,member_id
FROM ranked
WHERE rn=1;Watch for: DISTINCT on all columns cannot remove retries whose id or ingested_at changed.
build it step by step
Each step changes one thing. Run them in order and watch the result change.
Find event retries. Logical event a has more than one physical row.
step-1.sqlSELECT * FROM social_events WHERE event_key='a' ORDER BY ingested_at,id;
Number versions. The latest ingestion wins; id breaks timestamp ties.
step-2.sqlSELECT id, event_key, ingested_at, ROW_NUMBER() OVER(PARTITION BY event_key ORDER BY ingested_at DESC,id DESC) AS rn FROM social_events ORDER BY event_key,rn;
Keep one version. DISTINCT on all columns cannot remove retries whose id or ingested_at changed.
step-3.sqlWITH ranked AS( SELECT *, ROW_NUMBER() OVER(PARTITION BY event_key ORDER BY ingested_at DESC,id DESC) AS rn FROM social_events ) SELECT id,event_key,member_id FROM ranked WHERE rn=1