Delete duplicate rows from table with no unique key

后端 未结 5 437
误落风尘
误落风尘 2021-01-13 09:46

How do I delete duplicates rows in Postgres 9 table, the rows are completely duplicates on every field AND there is no individual field that could be used as a unique key so

5条回答
  •  借酒劲吻你
    2021-01-13 10:43

    Since you also need to avoid duplicates in the future, you could add a surrogate key and a unique constraint while dedupping:


    -- add surrogate key
    ALTER TABLE releases_labels
            ADD column id SERIAL NOT NULL PRIMARY KEY
            ;
    
    -- verify
    SELECT * FROM releases_labels;
    
    DELETE FROM releases_labels dd
    WHERE EXISTS (SELECT *
            FROM releases_labels x
            WHERE x.label = dd.label
            AND x.release_id = dd.release_id
            AND x.catno = dd.catno
            AND x.id < dd.id
            );
    
    -- verify
    SELECT * FROM releases_labels;
    
    -- add unique constraint for the natural key
    ALTER TABLE releases_labels
            ADD UNIQUE (label,release_id,catno)
            ;
    
    -- verify
    SELECT * FROM releases_labels;
    

提交回复
热议问题