How can window functions, specifically ROW_NUMBER(), be used for deduplication in SQL?
Last updated
Number rows with
ROW_NUMBER() OVER (PARTITION BY dup_keys ORDER BY ...), where the partition defines a duplicate and the order picks which copy survives (e.g. newest). Keeprn = 1.Use
ROW_NUMBER()rather thanRANK()to guarantee exactly one survivor. Add a tiebreaker so the survivor is deterministic.To delete duplicates, wrap it in a CTE and run
DELETE FROM cte WHERE rn > 1(PostgreSQL, SQL Server).
- https://www.devart.com/blog/sql-interview-questions-and-answers.html
- https://interviewkickstart.com/blogs/interview-questions/sql-interview-questions
- https://www.simplilearn.com/top-sql-interview-questions-and-answers-article
- https://intellipaat.com/blog/interview-question/sql-interview-questions/
- https://www.naukri.com/code360/library/sql-interview-questions
- https://www.weekday.works/post/advanced-sql-interview-questions
- https://interviewkickstart.com/blogs/interview-questions/sql-interview-questions-for-experienced-professionals
- https://medium.com/@anjalimishraa17/top-50-sql-database-interview-questions-the-complete-deep-dive-c5a6c9c1d728
- https://www.tryexponent.com/blog/data-engineering-interview
- https://www.interviewquery.com/interview-guides/lime-data-scientist