2

I need to delete from a table rows that have the same value on a specified field ignoring case. For example if I have a row that has 'foo' as value for a field and another row that has 'Foo' as value for the same field, I want to delete only one of these rows (keeping 1 row).
I've tried something like this:

delete from table t1 
where exists (select 1 
              from table t2 
              where t1.key <> t2.key 
                and t1.field ILIKE t2.field)

but this deletes the other row too.
Are there any suggestions?

2 Answers 2

3

Just change <> by <:

DELETE
  FROM table t1 
 WHERE exists (
    SELECT 1 
      FROM table t2 
     WHERE t1.key < t2.key 
       and t1.field ILIKE t2.field
 )

This way you keep the rows with the highest key. You also could use > to keep the records with the lowest key.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming key is the primary key of the table:

DELETE FROM the_table t1
WHERE t1.key not in (select min(t2.key)
                     from the_table t2
                     group by lower(t2.field));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.