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:
- Name the key that defines "the same thing". It may be one column or several.
- Name the rule that picks the winner: latest
updated_at, then latestloaded_atif there is a tie. - Number the rows within each key.
row_numbergives exactly one winner. - 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
- No tie-breaker. If two copies share the same
updated_atand you order by only that, which one survives is random. Addloaded_at, or an id, to theORDER BY. - Ordering ascending by mistake. "Latest" needs
desc. "First" needsasc. Check the first line of output by eye. SELECT DISTINCTis not deduplication by key. It removes only rows that are identical in every column. Two copies with differentupdated_atboth survive.GROUP BYandMAXmixing columns.max(updated_at)andmax(order_status)are computed separately, so the status may not be the one from the latest row. Use a window and keep whole rows.- Exact duplicates versus versions. Identical rows are noise to drop. Rows that differ are history. Ask which the prompt means.
- NULLs in the recency column. A NULL
updated_atsorts first in descending order in PostgreSQL, so it can win. Usenulls last. - Deleting on the wrong key. "Duplicate customers" by email is not the same as by customer id. Normalise case and whitespace before comparing.
Variations
- Keep the first. Flip the order, for example the first purchase per user.
- Count the removed rows.
count(*) - count(distinct key)gives the number of surplus copies. - Duplicates across several columns.
partition by customer_id, product_id. - Latest as of a date. Filter
updated_at <= datebefore ranking. DISTINCT ON. In PostgreSQL,select distinct on (key) * from t order by key, updated_at descreturns the first row of each key in one step. It is not available elsewhere.- Keep the latest but show the previous.
lagorleadin the same window, then filter.
In other warehouses
- Snowflake, BigQuery and Databricks have
QUALIFY:select * from t qualify row_number() over (partition by key order by updated_at desc) = 1. It removes the wrapper query. - SQL Server and MySQL need the CTE form. SQL Server also allows
deletethrough a CTE, which is the usual way to remove duplicates in place. - BigQuery has no
DISTINCT ON. UseQUALIFYor an array trick:array_agg(t order by updated_at desc limit 1)[offset(0)]. - Snowflake has
ARRAY_AGGandMAX_BY(col, ordering_col), which returns the value of one column at the row with the maximum of another.