Skip to main content

Find and safely delete duplicate records keeping the latest

Given users(id, email, created_at), write a query to find duplicate emails and delete older duplicates keeping only the newest row.

Official Reference

Model Answer & Explanation

WITH ranked AS (
  SELECT id,
         ROW_NUMBER() OVER (
           PARTITION BY lower(email) ORDER BY created_at DESC, id DESC
         ) AS rn
  FROM users
)
DELETE FROM users
WHERE id IN (SELECT id FROM ranked WHERE rn > 1);

Rank rows per email by created_at DESC, id DESC with ROW_NUMBER() and delete where rn > 1 (or use Postgres ctid/id self-join). Always preview with SELECT first, wrap in a transaction, and add a UNIQUE index afterward so duplicates cannot recur.

Follow-up Interview Question · How do you add a UNIQUE constraint on a huge table without blocking writes for minutes?

Module Context & References

PostgreSQL & Redis · Practice SQL & schema drills The classic SQL queries, locking patterns and optimization problems tested repeatedly
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.