Deduplicate Keep Latest Per Group

Remove duplicate rows keeping only the latest record per group using a window function row number filter.

SqlData Integrity

Code

sqlsnippet
12 lines
WITH ranked AS (
  SELECT
    *,
    ROW_NUMBER() OVER (
      PARTITION BY email
      ORDER BY updated_at DESC
    ) AS rn
  FROM users
)
SELECT * EXCEPT (rn)
FROM ranked
WHERE rn = 1;

What the code does

What runs is SELECT, with users and ranked as the object involved.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

Watch out for

  • Remember the evaluation order: WHERE first, window functions later — filtering on the latter needs another query level.

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
)
SELECT * EXCEPT (rn)
FROM ranked
WHERE rn = 1;

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`users`, `ranked` — referenced directly, no join needed.