Deduplicate Rows Keep Latest

Remove duplicate rows keeping the most recent version with window functions.

SqlData Integrity

Code

sqlsnippet
13 lines
WITH ranked AS (
  SELECT *,
    ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC) AS rn
  FROM users
)
DELETE FROM users
WHERE id IN (
  SELECT id FROM ranked WHERE rn > 1
);

-- Or keep in a new table
INSERT INTO users_dedup
SELECT * FROM ranked WHERE rn = 1;

What the code does

Several statements share this file — SELECT / INSERT / DELETE, with users, ranked and users_dedup among the objects involved.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause deciding which rows the statement applies to; a window function (OVER (…)) calculating values across rows while every row stays visible; an ORDER BY that fixes the output order.

What to watch for

  • Window functions are evaluated after WHERE and GROUP BY — their output is not visible to a same-level WHERE.

Applying it

The users table is the working surface here.

Statements that matter

WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC) AS rn
FROM users
)
DELETE FROM users
WHERE id IN (
SELECT id FROM ranked WHERE rn > 1
);
INSERT INTO users_dedup
SELECT * FROM ranked WHERE rn = 1;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`users`, `ranked`, `users_dedup` — referenced directly, no join needed.