Delete duplicate record from table in Postgresql

Asked

Viewed 7,687 times

2

Situation

Currently I performed a process twice in which it should be processed only once. So my table was populated twice with the same data.

tb_kardex
cd_kardex | cd_item

tb_kardex
| 1 | 45875 |
| 2 | 45876 |
| 3 | 45877 |
| 4 | 45875 |
| 5 | 45876 |
| 6 | 45877 |

Doubt

How to delete only the "second" record of the same item?

  • 2
  • 1

    So @Ricardo mysql != postgresql ... not sure if what applies in the other answer, can help this question, I voted to leave open, but maybe someone who understands postgresql can say your opinion :) - I will wait

  • @Guilhermenascimento I took the test and it didn’t work. Just like in reply

  • @Guilhermelautert, I made a change in my answer, the fiddle he is with example data only, but delete correctly.

3 answers

5


Do it like this:

DELETE a FROM nomes AS a, nomes AS b WHERE a.nome=b.nome AND a.id < b.id

Code find here.

UPDATING

To postgresql 9.3 would do so: (Here a working Fiddle)

DELETE FROM tb_kardex a
  where exists (select 1 from tb_kardex b 
      WHERE a.cd_kardex=b.cd_kardex 
        AND a.cd_item < b.cd_item);

1

Solution

DELETE FROM tb_kardex
WHERE cd_kardex IN (
SELECT  cd_kardex
FROM
    (
        SELECT  cd_kardex,
            ROW_NUMBER() OVER 
            (PARTITION BY cd_item ORDER BY cd_kardex asc) AS rn -- CRIA UM CONTAGEM DE PARA CADA CD_ITEM REPETIDO
        FROM    tb_kardex                                       -- É IMPORTANTE A UTILIZAÇÃO DO ORDER PARA MANTER O RN 2
    ) A                                                         -- NO ULTIMO cd_kardex
WHERE   rn = 2
)

Altering

If you have done a process repeat several times having more than 2 Rows change the criteria rn > 1.

  • I also found this answer Guilherme. http://stackoverflow.com/questions/6025367/t-sql-deleting-all-duplicate-rows-but-keeping-one

  • Our that which had not seen this oo.

  • @Did Guilhermelautert help? I did not risk an answer because it is postgree.

  • @Marconi yes that’s the way I solved

  • Good question :).

0

According to this reply on Soen you can create a temporary table and use DISTINCT:

CREATE TABLE tmp ...
INSERT INTO tmp SELECT DISTINCT * FROM t;
DROP TABLE t;
ALTER TABLE tmp RENAME TO t;

I recommend you take a backup first

Browser other questions tagged

You are not signed in. Login or sign up in order to post.