Home › Interview Questions › How can you use ROW_NUMBER() to deduplicate rows b…

How can you use ROW_NUMBER() to deduplicate rows by email and keep the row with the smallest id, instead of using SELECT DISTINCT?

🟡 Medium Conceptual Junior level
2Times asked
Nov 2026Last seen
Nov 2026First seen

💡 Model Answer

You can use a window function to assign a row number to each row within a partition of email, ordered by id ascending. Then filter for rows where row_number = 1. For example: SELECT email, id FROM (SELECT email, id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM table) t WHERE rn = 1; This keeps the row with the smallest id for each email. DISTINCT only removes exact duplicates; it does not allow you to choose a specific row when duplicates exist. The complexity is O(n log n) due to sorting, but it is efficient for large datasets when indexed properly.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500