SQL

Identify and Delete Duplicate Records (Keep One)

Learn how to find and safely remove duplicate rows from a SQL table while keeping one distinct record, essential for data integrity in web applications.

WITH CTE AS (
    SELECT 
        column1, column2, 
        ROW_NUMBER() OVER (PARTITION BY column1, column2 ORDER BY id) as rn
    FROM 
        your_table
)
DELETE FROM CTE WHERE rn > 1;
How it works: This SQL query provides a method to identify and delete duplicate records from a table, ensuring only one unique entry remains. It uses a Common Table Expression (CTE) and the `ROW_NUMBER()` window function. `PARTITION BY column1, column2` groups rows by the columns that define a 'duplicate', and `ORDER BY id` (assuming `id` is a primary key) determines which row within each group is kept. Rows with `rn > 1` are duplicates and are subsequently deleted, leaving only the first occurrence.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs