Deduplicate Keep Latest Per Group
Remove duplicate rows keeping only the latest record per group using a window function row number filter.
Code
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:
WHEREfirst, 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- `users`, `ranked` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.