Using a window function, how would you find duplicate rows in a table using SQL?
💡 Model Answer
You can use the ROW_NUMBER() window function to assign a unique sequence number to each row within a partition defined by the columns that should be unique. Rows with a row number greater than 1 are duplicates. Example:
SELECT *
FROM (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY col1, col2, col3 ORDER BY id) AS rn
FROM my_table t
) dup
WHERE rn > 1;This query partitions the table by the columns that define uniqueness (col1, col2, col3). The ORDER BY clause can be any deterministic column, often the primary key. Complexity is O(n log n) due to sorting within each partition, but most RDBMS implement window functions efficiently. The result returns all duplicate rows; you can then decide to delete or update them as needed.
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