-1

I have a table with some data inserted in it. The issue is that there are many rows that are equal to other rows and I want to delete them leaving just one of those rows. For example:

Table Person

    name       pet
---------------------------
    Mike       Dog
    Kevin      Dog
    Claudia    Cat
    Mike       Dog
    Mike       Dog
    Kevin      Snake

As you can see, we can see multiple times that Person named Mike has a Dog. But I would like to see it only once. So the output I'll want after update this table is:

    name       pet
---------------------------
    Mike       Dog
    Kevin      Dog
    Claudia    Cat
    Kevin      Snake

How can this be done?

GMB
  • 216,147
  • 25
  • 84
  • 135
user157629
  • 624
  • 4
  • 17

2 Answers2

1

You can do this with exists. In apparent absence of a primary key, system column ctid can be used:

delete from mytable t
where exists (
    select 1
    from mytable t1
    where t1.name = t.name and t1.pet = t.pet and t1.ctid > t.ctid
);
GMB
  • 216,147
  • 25
  • 84
  • 135
0

The simplest method is probably to recreate the table:

create table temp_t as 
    select distinct name, pet
    from t;

truncate table t;   -- back it up first!

insert into t (name, pet)
    select name, pet
    from temp_t;

create unique index unq_t_name_pet on t(name, pet);

The last step is to prevent this problem in the future.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786