Remove duplicate rows from database

This snippet is particularly for Postgres (that database I am currently using and didn’t tested it in other, but should work. At most you have to change the syntax a little). I have to remove duplicated entries for a duplicated_column

DELETE FROM table_name
WHERE id NOT IN (
    SELECT MIN(id)
    FROM table_name
    WHERE created_at > 'from_date' AND created_at < 'to_date'
    GROUP BY duplicated_column
    )
AND created_at > 'from_date' AND created_at < 'to_date';

So, change table_name with the name of your table and duplicated_column with the column where you have duplicates. Running the query from .. to date is a good idea if the duplicates are only for a given period of time and your table has a lots of records.

Tagged with: , ,
Posted in Databases, Postgres

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Sites
Categories
Archives