Skip to content
Discussion options

You must be logged in to vote

You can use a window function with ROW_NUMBER().

Example table: users(id, email, created_at)

DELETE FROM users
WHERE id NOT IN (
SELECT id FROM (
SELECT id,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC) AS rn
FROM users
) t
WHERE rn = 1
);

This assigns a rank inside each email group and keeps only the newest record (rn = 1).

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by suyXcode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants