Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete ALL of the duplicate rows in Posgresql ( not leave a single )

I would like to delete rows from my database that have the same name. I’ve checked Stackoverflow and found something like this:

DELETE
FROM my_table mt1 USING my_table mt2
WHERE mt1.my_name = mt2.my_name AND mt1.unique_id<mt2.unique_id;

This of course works but leaves one row. I have a request:

If there are rows with duplicate rows I have to remove ALL of them (not leave one).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use GROUP BY with a HAVING clause as subquery:

DELETE
FROM my_table 
WHERE my_name IN 
(SELECT
    my_name
FROM
    my_table
GROUP BY
    my_name
HAVING 
    COUNT(*) > 1);

Try out: db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading