Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 92/ 160
05. Window Functions & Analytical SQL

Deduplicating Tables Using ROW_NUMBER() OVER (PARTITION BY ...)

Keep one survivor row per key with ROW_NUMBER and filter rn = 1.

IntermediateROW_NUMBER Dedup · Survivor3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Group the copies, number them from best to worst, keep number 1 and remove the others.

Think of it like…

Cleaning up a contacts list with the same person saved three times: group the entries by phone number, keep the most recently updated one, and delete the rest.

Where you’ve seen it

A users table has the same email registered several times after a sign-up bug. You keep the most recently active account per lower-cased email, delete the rest, then add a unique index on LOWER(email) so it can't happen again.

Words you’ll hear

Duplicate key
The column or columns that define "the same record", such as email.
Survivor
The one row per key you keep, chosen by the ORDER BY.
rn > 1
The duplicates to remove.
Unique constraint
Prevents new duplicates once the data is clean.

Visual diagram

Loading interactive diagram

Theory & example queries

Finding and ranking duplicates

Start by measuring the problem: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1 shows which keys are duplicated and how badly. Then decide what makes two rows "the same"; often that means normalising the key, for example LOWER(TRIM(email)).

ROW_NUMBER() OVER (PARTITION BY key ORDER BY updated_at DESC, id DESC) numbers each group. The ORDER BY is a business decision: newest, oldest, most complete, or a preferred source. Add a unique tiebreaker such as id so the survivor is deterministic.

Reading the deduplicated dataQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  ranked AS (3    SELECT4      *,5      ROW_NUMBER() OVER (6        PARTITION BY7          LOWER(email)8        ORDER BY9          updated_at DESC,10          id DESC11      ) AS rn12    FROM13      users14  )15SELECT16  *17FROM18  ranked19WHERE20  rn = 1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/20
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
idemailupdated_atrn
12asha@example.com2026-11-18 10:20:001
28ben@example.com2026-11-17 14:05:001
35chen@example.com2026-11-19 08:45:001

Note: Illustrative survivor rows; SELECT * would include every remaining users column.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: PARTITION BY defines "same"; ORDER BY defines "best".

Deleting safely and preventing it again

Delete by primary key: compute the ranks in a subquery and delete the ids where rn > 1. In MySQL you can't select from the table you're deleting from directly (error 1093), but wrapping the ranking in a derived table works. Tables without a primary key can use PostgreSQL's ctid as a row identifier.

Run it inside a transaction and compare the deleted count with your earlier duplicate count before committing. Then add a unique constraint or unique index on the normalised key; otherwise the same bug creates new duplicates next week.

Delete the duplicates, keep the survivorQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1DELETE FROM users2WHERE3  id IN (4    SELECT5      id6    FROM7      (8        SELECT9          id,10          ROW_NUMBER() OVER (11            PARTITION BY12              LOWER(email)13            ORDER BY14              updated_at DESC,15              id DESC16          ) AS rn17        FROM18          users19      ) t20    WHERE21      rn > 122  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/22
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
DELETE 7

Note: Illustrative case with seven non-survivor duplicate rows; the real count depends on duplicate groups.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Delete by primary key inside a transaction, then add a unique index.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1GROUP BY

Measure the duplicates

Count rows per key with HAVING COUNT(*) > 1 to see how many keys are affected and how many extra rows there are.

SQL at this step
1GROUP BY2  LOWER(email)3HAVING4  COUNT(*) > 1
What to watch at this step
Know
how many rows you expect to delete
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

To remove duplicates while keeping one row per key, number the rows in each duplicate group with ROW_NUMBER() OVER (PARTITION BY key ORDER BY …). The row numbered 1 is the survivor; rows numbered 2 and above are the duplicates to filter out or delete. The ORDER BY decides which copy survives.

Why it matters: Duplicate rows from retried imports, double-submitted forms or messy joins are one of the most common data problems. DISTINCT can't help when the duplicates differ in some column (like updated_at). Interviewers ask this to see whether you can choose a survivor deliberately and delete safely.

When to reach for it

  • Cleaning up duplicate users, customers or events
  • Keeping the latest version of each record in a staging table
  • Reading one row per key in reports

When to avoid or be careful

  • ROW_NUMBER without a meaningful ORDER BY, which keeps a random copy
  • Deleting without checking the expected count first
  • Cleaning up without adding a constraint, so duplicates return

ROW_NUMBER vs DISTINCT vs DISTINCT ON

ROW_NUMBER() … rn = 1
Best for: Keeping one specific row per key when copies differ

Strengths: Full control over which copy survives; works for SELECT and DELETE.

Watch out: A little more code.

SELECT DISTINCT
Best for: Rows that are identical in every selected column

Strengths: Simplest.

Watch out: Can't pick a survivor; useless when any column differs.

DISTINCT ON (key) (PostgreSQL)
Best for: Reading one row per key in PostgreSQL

Strengths: Short: DISTINCT ON (email) … ORDER BY email, updated_at DESC.

Watch out: PostgreSQL-only, and not directly usable for DELETE.

Interview signals & numbers to know

When this topic comes up

  • “Remove duplicate rows but keep one”
  • “Keep the latest record per user”
  • Retried or double-processed imports
  • “Why doesn't DISTINCT remove these duplicates?”
  • MySQL error 1093

Benchmarks & rules of thumb

rn = 1 -
the survivor
rn > 1 -
the rows to delete
COUNT(*) - COUNT(DISTINCT key) -
number of extra rows

Common mistakes & follow-ups

Common interview mistakes

  • Using DISTINCT on rows that differ in a timestamp column and wondering why duplicates remain.
  • Leaving the survivor to chance with no tiebreaker in ORDER BY.
  • Deduplicating on email without normalising case and spaces, so Asha@X.com and asha@x.com both survive.

Likely interviewer follow-ups

  • How would you delete duplicates from a table that has no primary key?
  • How do you decide which duplicate to keep?
  • How would you stop duplicates from being created in the first place?
Interview tip: Answer in four steps: measure with GROUP BY/HAVING, rank with ROW_NUMBER and a deliberate ORDER BY, delete rn > 1 by primary key in a transaction, then add a unique index.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Deduplicating Tables Using ROW_NUMBER() OVER (PARTITION BY ...) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Moving Averages & Rolling Windows (7-Day, 30-Day Rolling Metrics)
Next topic
Top-N Records Per Category / Group