📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How would you remove duplicate rows from a SQL Server table while keeping the newest row for each key?

Intermediate Sql Intermediate

🎯 Key points

  • ROW_NUMBER partitioned by the business key
  • Deterministic ORDER BY with a tie-breaker
  • DELETE through the CTE where rn > 1
  • Batch large deletes to limit log growth and locking
  • Add a unique index afterwards to prevent recurrence

⏱ 30-second answer

Use a CTE with ROW_NUMBER() OVER (PARTITION BY <business key> ORDER BY CreatedAt DESC, Id DESC) and DELETE FROM cte WHERE rn > 1. The tie-breaker makes it deterministic. On a large table, delete in batches (DELETE TOP (5000) in a loop) to keep the log and locks small, back up or copy the rows first, and then add a unique constraint or index so duplicates can't come back.

🔍 What the interviewer is checking

Checks practical use of ROW_NUMBER with a CTE and safe deletion.

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me