Skip to content

Deduplication and latest row

Find repeated rows and keep exactly one per key, usually the latest, with ROW_NUMBER and a clear tie-breaker.

Practise: 10 questions

When you need it

"Find customers who appear twice", "keep the latest record per order", "remove duplicate loads", "current salary per employee", "most recent status". Words that signal it: "duplicate", "repeated", "latest", "most recent", "current", "one row per", "first".

Raw tables loaded from other systems often hold several copies of one entity, one per change or per retry. A clean model keeps one.

The shape of the query

Finding duplicates:

select key, count(*) as copies
from t
group by key
having count(*) > 1;

Keeping one row per key:

with ranked as (
  select *,
         row_number() over (partition by key order by <recency> desc, <tie-breaker> desc) as rn
  from t
)
select * from ranked where rn = 1;

Step by step:

  1. Name the key that defines "the same thing". It may be one column or several.
  2. Name the rule that picks the winner: latest updated_at, then latest loaded_at if there is a tie.
  3. Number the rows within each key. row_number gives exactly one winner.
  4. Filter to row number 1 in an outer query.
select order_id, count(*) as copies, min(updated_at) as first_seen, max(updated_at) as last_seen
from stg_orders
group by order_id
having count(*) > 1
order by copies desc, order_id
limit 10;
with ranked as (
  select order_id, customer_id, order_total, currency, order_status, updated_at, loaded_at,
         row_number() over (
           partition by order_id
           order by updated_at desc, loaded_at desc
         ) as rn
  from stg_orders
)
select order_id, order_status, order_total, currency
from ranked
where rn = 1
order by order_id
limit 10;

Traps interviewers look for

Variations

In other warehouses

Practise deduplication and latest row