Home › Interview Questions › Write a SQL query to find duplicate employee IDs i…

Write a SQL query to find duplicate employee IDs in the employee table, keep one record, and delete the remaining duplicates.

🟔 Medium Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

šŸ’” Model Answer

Use a CTE with ROW_NUMBER to identify duplicates and then delete the extra rows. Example:

WITH cte AS (

SELECT *, ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY employee_id) AS rn

FROM employee

)

DELETE FROM cte

WHERE rn > 1;

This keeps the first row for each emp_id and removes the rest. If you need to keep a specific row (e.g., the most recent hire_date), adjust the ORDER BY clause accordingly. Always back up the table before running deletes and consider using a staging table if the dataset is large. The operation runs in O(n log n) time due to the sorting required for ROW_NUMBER.

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